Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django design login
I want to design the login system when I try entering the web and press login button but nothing happens please help me this is my code enter image description here enter image description here enter image description here enter image description here -
Different representations of an object in the DRF
I have a model: class Schedule(LogSaveDeleteMixin, models.Model): name = models.CharField(max_length=40) start_date = models.DateTimeField(null=True, blank=True) class DeliveryChannel(LogSaveDeleteMixin, models.Model): name = models.CharField(unique=True, max_length=40) state = models.CharField(choices=DeliveryChannelState.choices, default='draft', max_length=15) schedule = models.ForeignKey(Schedule, null=True, on_delete=models.SET_NULL) And standard ModelSerializer: class DeliveryChannelsSerializer(serializers.ModelSerializer): class Meta: model = DeliveryChannel fields = '__all__' class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = '__all__' For read requests (GET) I want to receive schedule field as a nested serializer: { "id": 0, "name": "string", "state": "archived", "schedule": { "id": 0, "name": "string", "start_date": "2022-08-12T02:41:32.187Z", } } But for writing (POST, PUT) I want to get only schedule id: { "id": 0, "name": "string", "state": "archived", "schedule": 0 } I would like to know the best practices for do this -
Apache with nginx reverse proxy shutdown after a few hours running
I set up apache with nginx reverse proxy. After a few hours, apache somehow shutdown automatically. I checked around about memory with free however memory is sufficient. These are the log around the shutdown time. How can I stop this shutdown? [ N 2022-08-12 03:11:16.2891 22277/T1 age/Cor/CoreMain.cpp:1015 ]: Passenger core online, PID 22277 [Fri Aug 12 03:11:16.289552 2022] [core:warn] [pid 22268] AH00098: pid file /var/run/apache2/apache2.pid overwritten -- Unclean shutdown of previous Apache run? [Fri Aug 12 03:11:16.292287 2022] [mpm_prefork:notice] [pid 22268] AH00163: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1d Phusion_Passenger/6.0.4 configured -- resuming normal operations [Fri Aug 12 03:11:16.292317 2022] [core:notice] [pid 22268] AH00094: Command line: '/usr/sbin/apache2' [ N 2022-08-12 03:11:17.2347 22245/T1 age/Cor/TelemetryCollector.h:531 ]: Message from Phusion: End time can not be before or equal to begin time [ N 2022-08-12 03:11:17.2860 22245/T1 age/Cor/CoreMain.cpp:1325 ]: Passenger core shutdown finished [ E 2022-08-12 03:11:19.3253 22277/T5 age/Cor/SecurityUpdateChecker.h:521 ]: A security update is available for your version (6.0.4) of Phusion Passenger. We strongly recommend upgrading to version 6.0.14. [ E 2022-08-12 03:11:19.3254 22277/T5 age/Cor/SecurityUpdateChecker.h:526 ]: Additional security update check information: - [Fixed in 6.0.14] [CVE-2018-25032] zlib before 1.2.12 allows memory corruption when deflating (i.e., when compressing) if the input has many distant matches. - [Fixed in 6.0.14] … -
How can I use Nginx server blocks and Django?
I'm following the guide from https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04 However, when I link my home.html file in my django app's template folder, it doesn't load the css files and it doesn't understand any of the "{& &}" syntax. How can I configure my nginx server block to load my django app properly? my /etc/nginx/sites-available/myonlinefp.com file: server { root /home/stelity/myonlinefp/foodpantry/templates/; index index.html index.htm index.nginx-debian.html home.html; server_name myonlinefp.com www.myonlinefp.com; location / { try_files $uri $uri/ =404; } location /media { alias /home/stelity/myonlinefp/foodpantry/media/; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/myonlinefp.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/myonlinefp.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.myonlinefp.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = myonlinefp.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name myonlinefp.com www.myonlinefp.com; return 404; # managed by Certbot } -
How can i pass the table values to modal in Django?
When the edit option is clicked in the project, I want to transfer all the values in the relevant row into the modal, how can I do this? here table body <tbody class="list form-check-all"> {% for x in model %} <tr> <td class="id">{{x.name}}</td> <td class="company_name">{{x.phonenumber}}</td> <td class="leads_score">{{x.note}}</td> <td class="phone">{{x.status}}</td> <td class="location">{{x.callname}}</td> <td class="date">{{x.dataname}}</td> <td> <ul class="list-inline hstack gap-2 mb-0"> <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit"> <a class="edit-item-btn" href="#showModal" data-bs-toggle="modal"><i class="ri-phone-line fs-16"></i></a> </li> </ul> </td> </tr> {% endfor %} </tbody> and here my modal <div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header bg-light p-3"> <h5 class="modal-title" id="exampleModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button> </div> <form action=""> <div class="modal-body"> <input type="hidden" id="id-field" /> <div class="row g-3"> <div class="col-lg-12"> <div> <label for="leadname-field" class="form-label">Name</label> <input type="text" id="leadname-field" class="form-control" placeholder="Enter Name" required /> </div> </div> <!--end col--> <div class="col-lg-12"> <div> <label for="company_name-field" class="form-label">Company Name</label> <input type="email" id="company_name-field" class="form-control" placeholder="Enter company name" required /> </div> </div> <!--end col--> <div class="col-lg-6"> <div> <label for="leads_score-field" class="form-label">Leads Score</label> <input type="text" id="leads_score-field" class="form-control" placeholder="Enter lead score" required /> </div> </div> <!--end col--> <div class="col-lg-6"> <div> <label for="phone-field" class="form-label">Phone</label> <input type="text" id="phone-field" class="form-control" placeholder="Enter phone no" required /> </div> </div> <!--end col--> <div class="col-lg-12"> <div> … -
How can I load a class dynamically in Django
I have a project like below: myProject myApp migrations templates admin.py apps.py models.py modules.py class_A class_B class_C urls.py views.py I would try to load a class from modules.py dynamically in my views.py like below: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render def index(request, claz): # claz would be one of class_A, class_B or class_C mod = __import__("modules."+claz) fun = mod() But I always get errors like below: Request Method: GET Request URL: http://127.0.0.1:8000/myApp/class_A/ Django Version: 4.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'modules' Can anyone help me, Thanks a lot. -
How do I detect if my user has uploaded an ImageField or FileField?
I have the following model and function to set the upload paths for either image files or other files (which will be audio files). def upload_to(instance, filename): # Check for image or sound file and put in appropriate directory if isinstance(instance, models.ImageField): print("detected image file") return "x/img/%s" % (filename) else: print("detected non-image file") return "x/aud/%s" % (filename) class Tile(models.Model): image = models.ImageField(upload_to=upload_to, default="../static/x/img/default.svg") sound = models.FileField(upload_to=upload_to, null=True, blank=True) The final condition in upload_to is not correct, I realize, as instance is an instance of the tile object with all fields, but I'm not sure what to do in the upload_to function to find out if the file that was just uploaded by the user is an ImageField or FileField. -
Django Ajax form submission, how to get a specific model field from a form
For my project I need to be able to submit a form through ajax without refreshing the page. I have a model called Post with three fields: animal, image, and description. here is a picture of my model class Post(models.Model): BISON = 'Bison' WOLF = 'Wolf' ELK = 'Elk' BLACKBEAR = 'Black Bear' GRIZZLY = 'Grizzly Bear' MOOSE = 'Moose' MOUNTAINLION = 'Mountain Lion' COYOTE = 'Coyote' PRONGHORN = 'Pronghorn' BIGHORNSHEEP = 'Bighorn Sheep' BALDEAGLE = 'Bald Eagle' BOBCAT = 'Bobcat' REDFOX = 'Red Fox' TRUMPETERSWAN = 'Trumpeter Swan' YELLOWBELLIEDMARMOT = 'Yellow-bellied Marmot' RIVEROTTER = 'River Otter' LYNX = 'Lynx' SHREW = 'Shrew' PIKA = 'Pika' SQUIRREL = 'Squirrel' MULEDEER = 'Mule Deer' SANDHILLCRANE = 'Sandhill Crane' FLYINGSQUIRREL = 'Flying Squirrel' UINTAGROUNDSQUIRREL = 'Uinta Ground Squirrel' MONTANEVOLE = 'Montane Vole' EASTERNMEADOWVOLE = 'Eastern Meadow Vole' BUSHYTAILEDWOODRAT = 'Bushy-tailed Woodrat' CHIPMUNK = 'Chipmunk' UINTACHIPMUNK = 'Uinta Chipmunk' WHITETAILEDJACKRABBIT = 'White-tailed Jackrabbit' BEAVER = 'Beaver' AMERICANMARTEN = 'American Marten' MOUNTAINCHICKADEE = 'Mountain Chickadee' BOREALCHORUSFROG = 'Boreal Chorus Frog' CUTTHROATTROUT = 'Cutthroat Trout' GREATHORNEDOWL = 'Great Horned Owl' SNOWSHOEHARE = 'Snowshoe Hare' ROCKYMOUNTAINELK = 'Rocky Mountain Elk' NORTHWESTERNWOLF = 'Northwestern Wolf' BLACKFOOTEDFERRET = 'Black-footed Ferret' WOLVERINE = 'Wolverine' ANIMALS = [ (BISON, ('Bison')), … -
I can seeimage locally in django It's not visible in the deployment environment. What should I do?
enter image description here In the development environment, there's no problem It's being uploaded. However, if you upload it to the server, you can write a post it. I can't see the picture. nginx.conf worker_processes auto; events { } http { client_max_body_size 100M; keepalive_timeout 3000; server { listen 80; client_body_buffer_size 256k; include mime.types; location /static/ { alias /data/static/; } location /media/ { alias /data/media/; } client_max_body_size 100M; location / { proxy_pass http://django_container_gunicorn:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; } } } What should I do? -
Format warning in unit test as a import of customized app comes after loading settings
In a Django project's unit test, we need to configure the settings to direct to ourapp by INSTALLED_APPS and to prevent the below run-time error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. The line of from ourapp.rest.views import retrieve_timerange gets a formatting warning saying PEP 8: E402 module level import not at top of file. However, the import line depends on the INSTALLED_APPS of the settings, so it must come after the configuration action above. I wonder if there is an elegant way to resolve this formatting issue. Sample source code of the unit test: import os import django from django.conf import settings import unittest from unittest import TestCase os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ourproject.settings") django.setup() from ourapp.rest.views import retrieve_timerange class TestViews(TestCase): def setUp(self): ... def __run_get_test(self): ... -
django: m2m field may not be empty
Students can be assigned to many groups. One student can be assigned to many groups One Group can hold many students. With code below I can create Student with no group or assigned to some groups. I can change everything with success, exept... Exept that I can not remove all groups assigned to student. I assume that some student can unsubscribe from all groups. But django don't like that and throw error: {'groups': [ErrorDetail(string='This list may not be empty.', code='empty')]} Code: Models: class Group(models.Model): group_name = models.CharField(max_length=30, unique=True, null=True, blank=True) class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) groups = models.ManyToManyField(Group) Create Student: new_student = Student.objects.create( first_name = request.data["first_name"], last_name = request.data["last_name"], ) groups_id = request.data["group_id"] if(groups_id): for group_id in groups_id: new_student.groups.add(group_id) Change Student: def change_student(request, id): student_to_change = Student.objects.get(id=id) serializer = StudentSerializer( instance=student_to_change, data={ 'first_name': request.data["first_name"], 'last_name': request.data["last_name"], 'groups': request.data["groups"], } ) if serializer.is_valid(): serializer.save() And when I try to execute change_student with for example: request.data : {'id': 16, 'first_name': 'John', 'last_name': 'Smith', 'groups': []} I get {'groups': [ErrorDetail(string='This list may not be empty.', code='empty')]} error And serializers: class GroupSerializer(ModelSerializer): class Meta: model = Group fields = '__all__' class StudentSerializer(ModelSerializer): class Meta: model = Student fields = '__all__' -
Django-tables2: How to ensure consistent ordering when sorting?
When sorting the table by clicking on a header, if there are rows that have the same value, the order can not be consistent from one query to another. Is there a way to specify a "secondary" sorting criteria? For example, when user clicks on the price header to sort rows by price, behind the scene I'd like to have ordering = (price, pk) sothat the result is guarantee to be the same, given the same queryset. For now, I succeeded with price = tables.Column(order_by=["price", "id"]). However, doing this for every column is tedious, there must be a better way. Thanks. -
Re-usability of code between django and django rest framework
I have been assigned a project which has two versions of it: older one is written in django and new one written in django rest framework. I am quite new to both django and drf. While going through both codebase, I came across following code in one of the views.py in new drf version: def get_xyz(request): # some business logic return HttpResponse(json.dumps({ ... }) , content_type="application/json" , status=status.HTTP_200_OK) Then in older version of the app, I found function with exactly same above structure in its views.py. This created following confusions in me: Can we use function based views (as above) written in (non-drf) django app as it is in drf based app? Can we use class based views (as shown below) from non-drf django app as it is in the drf based app? class AbcClass(View): def get(self, request): # business logic return HttpResponse(json.dumps({ ... }) , content_type="application/json" , status=status.HTTP_200_OK) def post(self, request): # business logic return HttpResponse("success", status.HTTP_200_OK) Does all django framework (non-rest) classes (like View above) work perfectly in drf? Can we make frontend app written in react (or angular) send requests and receive responses from old django app (similar to how frontend apps built with these UI frameworks … -
Why can't I filter the data by one known in django&
I have a painted filter in view.py which works wonderfully. When I use a common abbreviation in html code, like {{form.as_p}} or {{form|crispy}}, then I can find the data I need, according to one known one. In my case, this is by course, by semester, by type of subject, by institute, and so on, and when I start writing my html code, in order for the search to give the correct answer, all fields must be filled in, although in forms and models I determined that all fields are not required, it turns out that an error in the html code, but I do not know where( veiws.py: def buy_files(request): bdfiles = FeedFile.objects.all() # bdfiles = UploadFile.objects.all() form = FileFilterForm(request.GET) if form.is_valid(): if form.cleaned_data["number_course"]: bdfiles = bdfiles.filter(feed__number_course = form.cleaned_data["number_course"]) if form.cleaned_data["number_semestr"]: bdfiles = bdfiles.filter(feed__number_semestr = form.cleaned_data["number_semestr"]) if form.cleaned_data["subjectt"]: bdfiles = bdfiles.filter(feed__subjectt = form.cleaned_data["subjectt"]) if form.cleaned_data["type_materials"]: bdfiles = bdfiles.filter(feed__type_materials = form.cleaned_data["type_materials"]) if form.cleaned_data["institute"]: bdfiles = bdfiles.filter(feed__institute = form.cleaned_data["institute"]) return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) html code: <div style="float: right; margin-bottom: 10%; margin-top: 10%;" class="form-group row" data-aos="fade-up"> <form action="" method="get" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label">Курс: </label> {{ form.number_course }}</p> <div class="form-error">{{ form.number_course.errors }}</div> <p><label class="form-label">Семестр: </label> {{ form.number_semestr }}</p> … -
Reverse for 'update' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['update/(?P<id>[0-9]+)/\\Z']
I am trying to update my ActiveMember model which has a OneToOneField with Members. I am running into this error. Reverse for 'update' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)/\Z'] I am new to django and not sure how to solve it. forms.py from dataclasses import fields from random import choices from socket import fromshare from django import forms from django.forms import ModelForm, DateField, widgets from .models import Member, ActiveMember from datetime import datetime, timedelta class MemberForm(ModelForm): class Meta: model = Member fields = ( 'full_name', 'email', 'phone', 'image', 'date_created', ) def __init__(self, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['email'].required = False self.fields['date_created'].disabled = True class ActiveMemberForm(ModelForm): class Meta: model = ActiveMember fields = ( 'member', 'start_date', 'end_date', 'status', ) widgets = { 'start_date': widgets.DateInput(attrs={'type': 'date'}), 'end_date': widgets.DateInput(attrs={'type': 'date'}), } models.py from django.db.models.signals import pre_save from django.dispatch import receiver import os from django.db import models from django.utils import timezone from datetime import datetime, timedelta from django.utils.text import slugify from .helper import upload_to_image_post # Create your models here. def default_start_time(): #now = datetime.now() now = timezone.now() start = now.replace(hour=23, minute=59, second=0, microsecond=0) return start if start > now else start + timedelta(days=1) class Something(models.Model): timestamp … -
Authorization header is not sending when using Swagger documentation on drf-spectacular
I'm using drf-spectacular to document and test my endpoint. My code look like this: @extend_schema( parameters=[ OpenApiParameter(name='Authorization', description='Authorization token', required=True, type=str, location=OpenApiParameter.HEADER), OpenApiParameter(name='my-key1', description='My key 1 info', required=True, type=str, location=OpenApiParameter.HEADER), OpenApiParameter(name='my-key2', description='My key 2 info', required=True, type=str, location=OpenApiParameter.HEADER), ], description='Info about the endpoint', responses={ 200: inline_serializer( name='Successfull response', fields={ "result_code": serializers.IntegerField(default=200), "result_description": serializers.CharField(default="Transaccion Exitosa"), "data": DocumentSerializer(many=True), } ), }, ) @api_view(["GET"]) def my_endpoint_function(request): pass As you can see I'm declaring 3 headers parameters, Authorization, my-key1 and my-key2. But when I try to use the Swagger documentation only my-key1 and my-key2 are sending. Here's an example: As you can see in the Swagger documentation I'm sending the three headers I mentioned above, but in the curl only two of them are sending. Does anyone know how to fix this? I need to test my endpoints in the documentation. Thank you for your time. -
Django REST framework: error in HTML form in browsable API
I have this model: class WeaponClass(models.Model): """Table with all possible weapon classes.""" label = models.CharField(max_length=32) acronym = models.CharField(max_length=8) class Meta: ordering = ['id'] verbose_name_plural = 'weapon classes' def __str__(self): return f"{self.label}, {self.acronym}" with this serializer: class WeaponClassSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="weapon_classes-detail") class Meta: model = WeaponClass fields = ['url', 'label', 'acronym'] Now, I have player, that has weapon class: class PlayerSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="players-detail") user = UserSerializer() weapon_class = WeaponClassSerializer() class Meta: model = Player fields = ['url', 'user', 'weapon_class'] When I display player, everything is working perfectly how I want it, except for one thing. When I view browsable API from django rest framework, Weapon Class name in HTML form is outputting <BoundField value=Medium Bruiser errors=None>. It should output 'Weapon Class', just like the part with 'User'. When I open Weapon Class, title on that page is normal, it says 'Weapon Class Instance', same as 'Player Instance' in pictures below. Its not affecting anything, but I'm really wondering why is it doing this: I circled the problem. -
Django matching query does not exist after creating superuser account
i'm working on someone code, after migration i create superuser account but EC_Admins matching query does not exist after login. here is my views @login_required(login_url='home') @staff_member_required(login_url='home') def adminhome(request): adminhome.username = request.session['admin_id'] a = EC_Admins.objects.get(ecadmin_id=adminhome.username) adminhome.adminimage = a.ecadmin_image return render(request,'admin/adminhome.html',{'username':adminhome.username,'image':adminhome.adminimage}) and log file File "C:\Users\user\Digital_Voting\EC_Admin\views.py", line 23, in adminhome a = EC_Admins.objects.get(ecadmin_id=adminhome.username) -
Import Error When Running Django From Windows
Trying to run Django (version 2.1) from Window’s Python 3.10.6. I received an Import Error from manage.py: ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" Have tried multiple things, with no luck: Installed Django on virtualenv through pip: PS C:\Users\nickg\vidly6> newenv\Scripts\activate (newenv) PS C:\Users\nickg\vidly6> newenv install django==2.1 (newenv) PS C:\Users\nickg\vidly6> django-admin startproject vidly6 . (newenv) PS C:\Users\nickg\vidly6> pip install virtualenv PS C:\Users\nickg\vidly9> code . Installed Django on pipenv: PS C:\Users\nickg\vidly6> pipenv install django==2.1 PS C:\Users\nickg\vidly6> pipenv shell Used instructions from Django’s site (created vidly9 file here so I could apply it to a different file): PS C:\Users\nickg\vidly9> vidly9-env\Scripts\activate.bat PS C:\Users\nickg\vidly9> python -m pip install django==2.1 PS C:\Users\nickg\vidly9> pipenv shell PS C:\Users\nickg\vidly9> django-admin startproject vidly9 . PS C:\Users\nickg\vidly9> code . Yesterday, when going through Django’s steps, I received a warning that the script was in the directory, but not in path: C:\Users\nickg\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts So I went to System Properties -> Environmental Variables -> User Variables. It was there that in the “Path” variable, and added it as a value. Didn't work either. -
Django: how to configure Apache to serve Django apps with mod_wsgi
I tried to set up a Django app with Apache and mod_wsgi, but ran into a problem that I have no ideas where is the cause. The app works fine with the command "python manage.py runserver", but when I tried to run it with Apache, I got the following errors in the Apache error log file. Current thread 0x00007fb4880ad940 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/data/anaconda3/envs/partsdb' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/data/anaconda3/envs/partsdb' sys.base_exec_prefix = '/data/anaconda3/envs/partsdb' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/data/anaconda3/envs/partsdb' sys.exec_prefix = '/data/anaconda3/envs/partsdb' sys.path = [ '/data/anaconda3/envs/partsdb/lib64/python38.zip', '/data/anaconda3/envs/partsdb/lib64/python3.8', '/data/anaconda3/envs/partsdb/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I have the following lines in an Apache conf file. WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb WSGIScriptAlias / /data/partsdb/partsdb/wsgi.py <Directory "/data/partsdb/partsdb"> <Files wsgi.py> Require all granted </Files> </Directory> I also replaced the following two lines in the Apache conf file WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb with the following two lines, but got the same errors. WSGIDaemonProcess partsdb … -
Django Form - Validator caused TypeError
I try to make validator for date and time via regex for data coming from Django Form. I can not figure out why I get 'type" is not iterable when I add validator o another field. views.py: def saveGate(request): if request.method == 'POST': form = NewGateForm(request.POST) # check whether it's valid: if form.is_valid(): g = Gate() g.save() gv = GateVersion() gv.gateInternalId = g gv.version = form.cleaned_data['version'] gv.state = form.cleaned_data['state'] gv.toBeReleased = form.cleaned_data['toBeReleased'] ga = GateAtributes() ga.gateInternalId = g ga.name = form.cleaned_data['nameOfGate'] ga.description = form.cleaned_data['description'] ga.gateExpression = form.cleaned_data['gateExpression'] ga.type = form.cleaned_data['type'] ga.save() gv.save() return HttpResponseRedirect('done/') else: return HttpResponse(ValidationError) else: raise Http404("Unexpected HTTP method.") url.py urlpatterns = [ path('', views.gates, name='gates'), path('detail/<str:gateInternalId>/', views.gateDetail, name='detail'), path('new/', views.newGate, name='new'), path('new/save', views.saveGate, name='save'), path('edit/', views.editGate, name='edit'), path('new/done/', views.done, name='done'), path('new/version/<str:gateInternalId>/', views.newVersion, name="newVersion"), path('new/version/saveVersion', views.saveVersion, name='saveVersion'), path('api/gates', views.apiGates) ] models.py class GateAtributes(models.Model): gateInternalId = models.ForeignKey(Gate, on_delete=models.CASCADE) atributesInternalId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=500, blank=True) description = models.CharField(max_length=5000, blank=True) gateExpression = models.CharField(max_length=150, unique=True, null=False) SHORT_TERM = 'ST' LONG_TERM = 'LT' GATE_TYPE_ENUM = [ (SHORT_TERM, 'Short-term'), (LONG_TERM, 'Long-term'), ] type = models.CharField(max_length=2, choices=GATE_TYPE_ENUM, default=SHORT_TERM) def __str__(self): return self.name def __iter__(self): return [ self.gateInternalId, self.atributesInternalId, self.name, self.description, self.gateExpression, self.type ] forms.py class NewGateForm(forms.Form): nameOfGate = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class': 'form-control … -
Generate a custom response for an API endpoint in Django Rest Framework using drf-spectacular
I'm trying to generate the documentation for an function based view in DRF using the drf-spectacular library. The response that I'm trying to generate should look like this: As you can see "data" is a list. I tried to do the following: class DocumentSerializer(serializers.Serializer): date = serializers.IntegerField(default=123) total_documents = serializers.IntegerField(default=1890) @extend_schema( parameters=[ OpenApiParameter(name='authorization', description='Authorization token', required=True, type=str, location=OpenApiParameter.HEADER), ], description='Info about the endpoint', responses={ 200: inline_serializer( name='Successfull response', fields={ "result_code": serializers.IntegerField(default=200), "result_description": serializers.CharField(default="Transaccion Exitosa"), "data": DocumentSerializer(), } ), }, ) @api_view(["GET"]) def my_endpoint_function(request): pass As you can see "data" should be a list of DocumentSerializer, but I don't know how to achieve that. The result I'm obtaining with the code above is the following: Because I don't know how to make that data has a list of DocumentSerializer. It will be great if you can help me, I've searching in the documentation but at this point I'm stuck. -
Fechas con Django
Tengo un formulario donde registro la fecha en que creo el formulario y me pide la fecha de cierra para editar, pero cuando creo el formulario me pide que le diligencia la fecha de cierre. ¿Como puedo hacer para que cuando envié el formulario del template me reciba el espacio en blanco y no me genere error. Estas son las dos fechas del modelo, el campo fecha, se diligencia al momento de crear el formulario, pero la fecha de cierre no sabemos cuando se va cerrar, pero enotnces si no coloco una fecha me sale un error. fecha = models.DateField(null=True) fecha_cierre = models.DateField(null=True, blank=True) Es posible que el campo sea vacío? -
Queryset from non-related model in __init__ modelform method
I have two model classes. They are not related models (no relationship). # models.py class Model1(models.Model): description = models.TextField() option = models.CharField(max_length=64, blank=False) def __str__(self): return self.option class Model2(models.Model): name = models.CharField(max_length=64, blank=False) def __str__(self): return self.name I have respective form from where I am submitting and saving data in my table. I want to use my Model2 data to fill-in 'option' field as select field, so I am introducing below init method. # forms.py class Model1Form(forms.ModelForm): def __init__(self, *args, **kwargs): all_options = Model2.objects.all() super(Model1Form, self).__init__(*args, **kwargs) self.fields['option'].queryset = all_options class Meta: model = Model1 fields = ('description', 'option') It does not render the dropdown on my template, so I am wondering whether it is right way to address the issue (acknowledging that models are not related to each other). -
How can I redirect to a page depend on different user group correctly by django?
I am creating a feature to let the banned user (user without any group) go to a specific page banned_alert when they click the "post", because they are not allowed to do so. But then when I test this feature, the Chrome shows This page isn’t working | the IP redirected you too many times. Can somebody tell me how to do it correctly? Did I miss any configuration? Below is my code snippets. Thank you for your time! base.html: (has_group function already works correctly somewhere else) {% load get_group %} {% if request.user|has_group:"mod" or request.user|has_group:"default" or user.is_staff %} <a class="nav-link" href="/create-post">Post</a> {% else %} <a class="nav-link" href="/banned_alert">Post</a> {% endif %} banned_alert.html: {% extends 'main/base.html' %} {% block title %}Your account has been banned by Admin{% endblock %} {% load crispy_forms_tags %} {% block content %} <h2>Please contact the Admin!</h2> {% endblock %} view.py def banned_alert(request): if request.method == 'GET': return redirect('/banned_alert') urls.py urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('sign-up', views.sign_up, name='sign_up'), path('create-post', views.create_post, name='create_post'), path('banned_alert', views.banned_alert, name='banned_alert'), ]