Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python-Docx - Jinja2: Populate word document without messing the template
I am trying to populate my word template with info from database. But it keep messing up the template. Any other way to make the result exactly the same as the template? template.docx result.docx Here's my code for views.py def save_devicedemoteapplication(request): samples = DeviceDemoteApplication.objects.all()[0:10] document = DocxTemplate("template.docx") context = { 'content': [], } for sample in samples: count = 0 samp= [count, sample.device.device_name, sample.device.asset_number, sample.device.device_model, sample.device.serial_number, sample.demote_reason, sample.demote_time, sample.device.buy_time, sample.technology_administrator, sample.quality_administrator] context['content'].append(samp) document.render(context) document.save('result.docx') return redirect('/DeviceDemoteApplication/') -
How to get uploaded file in views?
I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error FileNotFoundError: [Errno 2] No such file or directory: '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx but I have that file. How can I fix that? upload = Upload(file=f) content = ScanDocument(upload.file.path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text Note if I use url instead of path then it returns: FileNotFoundError: [Errno 2] No such file or directory: '/media/Meeting%20notes%20notes%20%(1).docx' -
Dynamically change db_table django Meta
Sorry for my English I have a table to manage list of database configurations. Table post in all db have same fields but different name. Eg. table post name is md_post, table post in other db is tdt_post. So, when I access a db configuration I want to remote that database. I did it! But how can I change tb_name in Meta Django Model? These Datatables configurations are non-permanent and may change when I add/update/delete record. I tried it, but it only works one time. Post._meta.db_table = `tdt_post` Post._meta.original_attrs['db_table'] = `tdt_post` When I change the db_table back to 'md_post', it doesn't work. I have looked at the following posts, but it doesn't solve my problem: Django model: change db_table dynamically Change table name for django model in runtime -
I am getting error when to limit foreign keys
Goal: I want to limit(20) the number of Students per Group. I was trying to make validation (based on this question - Limit number of foreign keys), but got a problem - it's working when I am trying to make 21 Student in group in my Django admin panel, but when I'm trying to change login(or other parameters) of Student (the group in this moment has 20 Students), who already in group it turns up an error, because it seems like I already have 20 students and trying to add new one def validate_number_of_students(value): if User.objects.filter(group=value).count() >= 20: raise ValidationError('Already 20 students in group (20)') class User(AbstractUser): role = models.CharField(max_length=max([len(role[0]) for role in ROLES]), choices=ROLES, default=USER, ) group = models.ForeignKey('structure.Group', on_delete=models.SET_NULL, related_name='users', blank=True, null=True, validators=(validate_number_of_students, ) ) I tried to use this method with constraint (limit number of foreign key using Django CheckConstraint) but get an error, maybe I'm doing something wrong? (I have two apps - structure with Group model and users with User model) models.CheckConstraint( name="limit_students_in_group", check=IntegerLessThan( models.Count("group", filter=models.Q(group=models.F("group"))), 20), ) -
Django - problem with saving data in Createview with ModelForm to non-default database
I've got problem with saving data to non-default database. In models.py I've got: grid_fs_storage = GridFSStorage(collection='tab_userinquiries', base_url='mydomain.com/userinquiries/',database='mongo_instance') class DocsUserInquiry(models.Model): query_pk = models.CharField(blank=False, null=False, unique=True, max_length=150, primary_key=True) # auto - calculated query_file_md5 = models.CharField(blank=False, null=True, unique=False, max_length=200) # auto - calculated query_file = models.FileField(upload_to='userinquiries',storage=grid_fs_storage,null=True) # auto from form In views.py: class UploadInquiryFileView(CreateView,LoginRequiredMixin): model=DocsUserInquiry template_name ='new_inquiry.html' success_message = "You've added your new Token successfully" form_class = UploadInquiryFileForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): file_name = request.FILES['query_file'].name print(f'file...{file_name}') q_pk = random_id() file_in = self.request.FILES.get('query_file') f_md5 = calculate_md5(file_in) form.instance.query_pk = q_pk form.instance.query_file_md5 = f_md5 form.save() return HttpResponse(self.success_message) The problem is every time when I submit form I've got Exception Type: TypeError Exception Value: database must be an instance of Database I've tried added this to post method: instance = form.save(commit=False) instance.save(using='mongo_instance') but the error is the same. Any ideas how to resolve this issue? NOTE: This issue is related only with modelform or when I use custom list of fields in view. When I'm using CreateView without ModelForm but with fields = 'all' and additionally with the logic passed to form_valid method of the view instead of post everything works fine. Then files are added to my mongo db. -
how to display first_name in database on django
`views.py from allauth.account.views import SignupView from .forms import HODSignUpForm class HodSignUp(SignupView): template_name = 'account/signup.html' form_class = HODSignUpForm redirect_field_name = '' view_name = 'hod_sign_up' def get_context_data(self, **kwargs): ret = super(HodSignUp, self).get_context_data(**kwargs) ret.update(self.kwargs) return ret forms.py from .models import Admin from po.models import User from allauth.account.forms import SignupForm class HODSignUpForm(SignupForm): first_name=forms.CharField(required=False) last_name=forms.CharField(required=False) class Meta: model= Admin fields = ['first_name','last_name'] def save(self,request): user = super(HODSignUpForm, self).save(request) user.is_hod = True user= User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name')) user.save() return user models.py from po.models import User class Admin(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=30, db_column='first_name') last_name = models.CharField(max_length=30, db_column='last_name') po.models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_active = models.BooleanField(default=True) is_hod= models.BooleanField(default=False) first_name = models.CharField(null=True, max_length=50) last_name=models.CharField(null=True, max_length=50) admin.py from po.models import User class Schooladmin(admin.ModelAdmin): list_display = ("id","is_active","is_hod","first_name","last_name") list_filter = ("is_active","is_hod") add_fieldsets = ( ('Personal Info', { 'fields': ('first_name', 'last_name') }), ) admin.site.register(User,Schooladmin) enter image description here i want this image show name but how does show firstname and lastname on database? -
Can't describe POST request with BaseHandler
sorry for my bad english get request works fine, the data is displayed correctly, but it's not possible to add new data, it shows a server error status 500 Class Test(models.Model): id = models.AutoField(u'id', primary_key=True) name = models.CharField(u'name', max_length=255, null=True) class Meta: db_table = u'test' verbose_name = u'test' verbose_name_plural = u'tests' Class TestHandler(baseHandler): def read(self, request, id=None): return self.model.object.all() enter image description here def create(self, request, id=None): f=Test(request.POST) new=f.save() return new POST http://127.0.0.1:8000/test/ 500 (INTERNAL SERVER ERROR) I tried this, but it doesn't work either: def create(self, request, id=None): new_test = SmartCheckpointVideo( id=request.POST['id'], name=request.POST['name'] ) new_test.save() return new_test and this def create(self, request, id=None): new_test = SmartCheckpointVideo( name=request.POST['name'] ) new_test.save() return new_test I don't understand how to work with BaseHandler, if there is detailed documentation, please share it -
DRF: many=True causes array instead of returning a regular object
I'm using a nested serializer to access the facility address of each facility. The only way the values will actually show is when i add many=true to the "LeadFacilityDetailFacilitySerializer". But the issue is that it will add [] around my address object. Which leads to "undefined" whjen i try to access the items inside my address object: {info.LeadFacilityDetailFacility.AddressInfo.City} serializers.py class LeadAddressSerializer(serializers.ModelSerializer): class Meta: model = FacilityAddress fields = ( "PrimaryAddress", "SecondaryAddress", "City", "RegionOrState", "PostalCode", ) class LeadFacilityDetailFacilitySerializer(serializers.ModelSerializer): AddressInfo = LeadAddressSerializer(source="fa", many=True) class Meta: model = Facility fields = ('mainimage', 'Name', 'AdministratorCell', 'AddressInfo') class LeadFacilityDetailSerializer(serializers.ModelSerializer): LeadFacilityDetailFacility = LeadFacilityDetailFacilitySerializer(source="assigned_facilities") class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'id', 'LeadFacilityDetailFacility') models.py class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=150, null=True, blank=True) SecondaryAddress = models.CharField(max_length=150, null=True, blank=True) City = models.CharField(max_length=150, null=True, blank=True) RegionOrState = models.CharField(max_length=50, null=True, blank=True) PostalCode = models.CharField(max_length=30, null=True, blank=True) Geolocation = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) -
Calling the list created using getlist on the form
In my Django project, I save the data in a field that I have made multiple selections to the database using the getlist function and the POST method. Then I pull this data from the database and print it on an html form, but I cannot access the list data properly unless I split it here. views.py def record_form(request): if request.method == "POST" and 'registrationSave' in request.POST: records = Records() records.medications = request.POST.getlist('medications') records.scale_used = request.POST.getlist('scale_used') records.save() return redirect('/index/tables') def editRecords(request,id): edit_records = Records.objects.get(id=id) if edit_records.medications is not None: edit_records.medications = edit_records.medications.split(",") if edit_records.scale_used is not None: edit_records.scale_used = edit_records.scale_used.split(",") institutionName = Institution.objects.all() medicationName = MedicationName.objects.all() return render(request,"update_record.html",{"Records": edit_records, "institutionName":institutionName,"medicationName":medicationName}) update.html <div class="col-4"> {% for medication in Records.medications%} <div class="mb-3 col"> <label for="">İlaç Adı:</label> <select class="form-select" name="medications" id="medications"> <option {% if medication == '{{medicationName.medicationName}}' %} selected {%endif%}>{{medication}}</option> {% if medicationName%} <p>{{medicationName}}</p> {% for medicationName in medicationName %} <option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option> {%endfor%} {%endif%} </select> </div> {%endfor%} </div> I'm sharing my code pieces above with you, and I'm leaving the screenshot of the update.html page below. How can I follow a method to avoid [ ] and ' ' signs? enter image description here Thank you in advance for your help -
Does a function based view in Django returning JSON response considered RESTful?
A function based view in Django which authenticates the user based on the sessionid and requests using X-CSRFToken(for POST calls) which returns data in JSON is considered RESTFul? I am currently not using djangorestframework for my project. -
Need Inline ManytoMany Field add in django admin
I am creating a manytomany field in my model and creating a Inline Tabular with though also. but on django admin it is showing dropdown. and if I add new then it shows a Popup. But I dont want Popup. Instead of that I want inline add as in case of Foreign Key. Thanks in advance. Please help... class ExamInline(admin.TabularInline): # classes = ['collapse'] model = Form.exam.through extra = 0 -
django-advanced-filters text contains not working
I would like to set a filter that gives me all items where "@test.com" is in the email. When setting up the filter, the field only allows me to select something from the autocomplete list of existing entries. Else it does not save. There is no possibility to add a custom string here. I am using python 3.10.4, django 3.0, django-advanced-filters 2.0.0 I tried to insert any different string but it would not save. I would expect the contains to allow for only a part of a string to compare and not to specify an existing string of the field that is already used. -
How to return choices tuple value in string format in django Admin panel
I've been trying to get tuple value from choices tuple of CharField() in Model to display in the Django Admin Panel row whenever a table is accessed I'm aware of the following answer... get_foo_display() but it returns the following error AttributeError: 'device_table' object has no attribute 'get_device_type_display' Here's the model: device_table(models.Model): device_type = ( ('AD' , 'Android'), ('IO' , 'iOS'), ('WD' , 'Windows'), ('MO' , 'MacOS'), ('LX' , 'Linux') ) user_device_type = models.CharField(choices = device_type, null = True, max_length=3) class Meta: verbose_name = ('Device Table') def __str__(self): return self.get_device_type_display() I'm running django 4.0.8 by the way -
Django -- connection to local postgresql to docker container
Hello everyone i try to connect local postgres db to the docker container in django project. as mention in this post it works on my local machine which is ubuntu 20.04 LTS but cannot run same project on ubuntu-server which is ubuntu 20.04 LTS. screenshots are give below pg_hba.conf postgres.conf Error in terminal this is my dockercompose file -
When using django's queryset union function, data in the queryset at the back may be lost
When using django's queryset union function, data in the queryset at the back may be lost. The structure of the model I used is as follows. class Genre(models.Model): name = models.CharField(max_length=50) class Top_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(max_length=200) genres = models.ManyToManyField(Genre, related_name="top_genre") year = models.IntegerField() ranking = models.IntegerField() class Now_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(null=True, max_length=200) genres = models.ManyToManyField(Genre, related_name="now_genre") year = models.IntegerField() ranking = models.IntegerField() Top_Movie.objects.all().union(Now_Movie.objects.all()) In the above situation, the genres field data of Now_Movie is lost. Now_Movie.objects.all().union(Top_Movie.objects.all()) In the above situation, genres field data loss of Top_Movie occurs. I don't know why this is happening. Please help. I solved the problem by not using union , but I want to know why this happened. My guess is that the ManyToManyField is causing something, but I don't know exactly why. -
Validation error ['clocked must be one off, one_off must set True']
I am trying to save periodic tasks using django_celery_beat package getting the above error, the code is as follows. Save uses post save signals class MailTask(models.Model): name = models.CharField(max_length=100, blank=True) subject = models.CharField(max_length=100) message = models.TextField() from_email = models.EmailField() recipient = models.EmailField() sent = models.BooleanField(default=False) time_to_send = models.DateTimeField() def schedule_mail_task(sender, instance, created, **kwargs): if created: clocked_schedule, created = ClockedSchedule.objects.get_or_create( clocked_time=instance.time_to_send, ) periodic_task = PeriodicTask.objects.create( clocked=clocked_schedule, name=f'instance.name+{instance.timestamp}', task='core.tasks.send_mail_func', enabled=True, ) post_save.connect(schedule_mail_task, sender=MailTask) -
How can I reach Django admin model stackedinlines in html tags?
I'm using stackedinline for for creating subtopic for each cancer type, in admin everything works fine, i can add subtopic for each type of cancer directly from cancer type creat/edit page, but I cant figure out how to display subtopic related to "parent" type in html template. P.S. I'm new in programming my models.py from django.db import models from ckeditor.fields import RichTextField class CancerType(models.Model): name = models.CharField(max_length=200, blank=False) image = models.ImageField(upload_to="static/assets/images/types") description = RichTextField(default="", blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Տեսակ" verbose_name_plural = "Տեսակներ" class SubTopic(models.Model): type = models.ForeignKey(CancerType, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=False) topic = RichTextField(blank=False, null=True) def __str__(self): return self.title class Meta: verbose_name = "Ենթաբաժին" verbose_name_plural = "Ենթաբաժիններ" admin.py rom django.contrib import admin from .models import CancerType, SubTopic admin.site.register(SubTopic) class SubTopicInline(admin.StackedInline): model = SubTopic extra = 0 class CancerTypeAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(CancerType, CancerTypeAdmin) type.html {% extends 'base.html' %} {% load static %} {% block content %} <img src="{% url 'home' %}{{ cancertype.image }}"> <h4>{{ cancertype.name }}</h4> <br> {{ cancertype.description|safe }} <br> {% for subtopic in object_list %}} {% if subtopic.type %}} {{ subtopic.title }} <hr> {{ subtopic.body }} {% endif %} {% endfor %} {% endblock %} -
how to stop run path again to join whith same path in django
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this i need help to solve this problem -
model for uploading and downloading file from specific category
I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. -
Python cli.py execution stuck: Unable to figure out the source
I'm trying tto deploy the following Django-rest api on gcp ubuntu 22.0.4 using python 3.9. https://github.com/OkunaOrg/okuna-api The enter setup is supposed to be done and get setup using a single command : python3.9 okuna-cli.py up-full The execution seems stuck at "Waiting for server to come up..." and doesn't proceed ahead. The setup should complete by stating "Okuna is live at "domain". Another important aspect of the setup is the 5 docker containers are running and working fine when i run the py file. I'm even able to access the database after creating a superuser. The code is as follows : import random import time import click import subprocess import colorlog import logging import os.path from shutil import copyfile import json import atexit import os, errno import requests from halo import Halo handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(name)s -> %(message)s')) logger = colorlog.getLogger('🤖') logger.addHandler(handler) logger.setLevel(level=logging.DEBUG) current_dir = os.path.dirname(__file__) KOSMOS_CLI_CONFIG_FILE = os.path.join(current_dir, '.okuna-cli.json') KOSMOS_CLI_CONFIG_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.okuna-cli.json') LOCAL_API_ENV_FILE = os.path.join(current_dir, '.env') LOCAL_API_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.env') DOCKER_COMPOSE_ENV_FILE = os.path.join(current_dir, '.docker-compose.env') DOCKER_COMPOSE_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.docker-compose.env') REQUIREMENTS_TXT_FILE = os.path.join(current_dir, 'requirements.txt') DOCKER_API_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api', 'requirements.txt') DOCKER_WORKER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'worker', 'requirements.txt') DOCKER_SCHEDULER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'scheduler', 'requirements.txt') DOCKER_API_TEST_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api-test', 'requirements.txt') CONTEXT_SETTINGS = … -
Where to verify the settings during startup
After settings.py executes, I need to check to make sure all the settings were found from the .env variables, and error out if they are not. Where's the appropriate place to put that logic? Right in settings.py? manage.py? -
Custome route in django admin
I wanted to customize my django admin route Not from /admin to something else but to add new clickable custom route inside admin panel Currently I have created superuser using python manage.py createsuperuser command. I can login to django admin panel , but what I want is to have a custom route to be displayed in left sidebar or anywhere else after logging into django admin panel. My custom route is like localhost:8000/my-view/ and my-view should be displayed somewhere in admin panel. TIA. -
Want to make code for inactive or idle user time in Python when he did not show any movement on screen and keyboard and mouse through
I am student and I am making an app regarding tracking time activity. So please help me to give an solution. I am finding out from last 4 days regarding the hints or code . I got one solution of my friend . but i am confuse that how to use this. If i use this and store that time so how could i make an object and api so i can display this time in frontend side. import sys if sys.platform == 'win32': from ctypes import * class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_int), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) if windll.user32.GetLastInputInfo(byref(lastInputInfo)): millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0 else: return 0 else: def get_idle_duration(): return 0 if __name__ == '__main__': import time while True: duration = get_idle_duration() print('User idle for %.2f seconds.' % duration) time.sleep(0.5) I am expecting that please help me to solve my solution. I am student and I am learning this. I am expecting an output like total idle time of computer is 1 hr or 2 hr . I already made code for tracking time for task/project time. -
I cannot install Django, And give "Installation failled"
I want to install Django,But when I run pipenv install django it create virtual environment and then give Installation Failed. Before try below codes I run pip install django to install Django. And there is no issue with internet connection. How do I fix this? I tried pip install django , pipenv install django -
django.urls.base.get_script_prefix() returns incorrect prefix when executed by apache
Python-3.8/Django-3.2/Mezzanine-6.0 application tries to access incorrect pages when executed by apache. In standalone mode (python manage.py runserver) it creates correct address /admin/page_types/basicpage/2677/change/ whereas in apache mode it creates address /admin/page_types/basi/admin/pages/page/2677/change/ in the same place. It seems to be the get_script_prefix() function in django/urls/base.py that returns incorrect prefix when accessing page 2677 in apache mode. Also it seems to be running the same main thread all the time in apache mode. Could it be the main reason ? Apache configuration: [django@tkpika03p ~]$ cat /etc/httpd/conf.d/pika.conf # # VirtualHost template # Files must have the .conf suffix to be loaded. # # NameVirtualHost statements can be added to /etc/apache2/listen.conf. # # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for requests without a known # server name. # <VirtualHost *:80> ServerAdmin palvelin.hallinta@<myDomain> ServerName pikaappm.<myDomain> ServerAlias tkpika03p.ad.<myDomain> # TODO: Missä tilanteissa tänne päädytään? Jos ei löydy wsgi/django # : takaa, palautetaan 404 ja haetaan toiselta serveriltä # : Teoriassa täältä ei siis lueta mitään? DocumentRoot /srv/www/htdocs # if not specified, the global error log is used ErrorLog /var/log/httpd/pika-error_log CustomLog /var/log/httpd/pika-access_log combined # TODO: Vaihdettava debug -> warn -> info, kun kaikki toimii LogLevel warn # …