Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the Middleware not processed on 404 page in Django?
So I've set up a path in my URL config: path( "kitten/", views.Kitten.as_view(), name="kitten", ), and a handler for missing URLs to the same view. handler404 = views.Kitten.as_view() I have some middleware which sets some context data: class CookieConsentMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_template_response(self, request, response): response.context_data["hasCookie"] = False return response and the view is very straightforward, class Kitten(TemplateView): template_name = "kitten.html" and the template prints the value of hasCookie. Visiting kitten/ correctly displays the value of hasCookie, but visiting a URL that doesn't exist, displays no value for hasCookie (whilst showing the right template) Adding debugging statements to the middleware, it becomes apparent that whilst process_view, process_template_response and process_exception are called for kitten/, none of these are called for URLs that don't exist, so no code is called to set the value of hasCookie. (__init__ is called regardless at app startup) Why does it not call the middleware when the URL is not found in the URLconf? -
Django query for column value search?
What is the Django query for this? DB data - col1 | Col2 ------------------------- sahil1 | Cat 1.2.3 sahil2 | 1.2.3-XY2 sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil5 | 9.8.4,1.2.3-XY2,9.8.7 sahil6 | Cat 1.2.3,9.8.2,1.2.3 I only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). And pattern "1.2.3" can be anywhere in column where column value can have comma separated values too. Desired Result - col1 | Col2 ------------------------- sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil6 | 1.2.3-XY2,9.8.2,1.2.3 When i am performing below Django query - col2_count = TableName.objects.filter(col2__contains="1.2.3") Getting all record but i only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). How do I implement this in Django? -
decode() function is not working "AttributeError: 'str' object has no attribute 'decode'"
Hi I am trying to fix my test case buy decode function is not working this is my code in test Django ```class RefreshView(APIView): serializer_class = RefreshSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: active_jwt = Jwt.objects.get( refresh=serializer.validated_data["refresh"]) except Jwt.DoesNotExist: return Response({"error": "refresh token not found"}, status="400") if not Authentication.verify_token(serializer.validated_data["refresh"]): return Response({"error": "Token is invalid or has expired"}) access = get_access_token({"user_id": active_jwt.user.id}) refresh = get_refresh_token() active_jwt.access = access.decode() active_jwt.refresh = refresh.decode() active_jwt.save() return Response({"access": access, "refresh": refresh})``` enter image description here -
Django + React Routes
Hello I have issues with my routes, I am trying to add Root to App.js (frontend) I keep getting Blankpage maybe the issue is minor but really can't find the solution. If i replace Root for BrowserRouter, it displays fine. I want to add Store to my application so that is why I need Root. This is the Code Code Image - APP.JS enter image description hereRoot.JS -
Field specific validation error on ListSerializer
Is there a way to raise field aware ValidationError on validate method of ListSerializer? In my case putted data might contain conflicting records, so I have to validate it. After raising such error it returns Non-field error, but I'd love to return list of validated data, where records are empty {} if everything is fine and records are like {'first_name': 'name must be unique withing request'} -
How to get Django Admin pulldown list to just show the first "order by" item instead of the models.py default?
I am working on a website-builder program. When the user creates a new page, he has to choose a language (English, French, German for example). In Django Admin, in the language admin, the user can set an order. The language model contains: order = models.PositiveSmallIntegerField(default=0, verbose_name='display order') In the page parameters in Django Admin, the user has to choose a language. The page model contains: language = models.ForeignKey(Language, default=0, on_delete=models.PROTECT, verbose_name='language') The problem I have is that when the user creates a new page in Django Admin, language with PK 0 is always selected by default, even though it's not the first in the list. Language 0 is always pre-selected by Django, and the user is unable to set the default language of new pages by setting the display order of the languages. What I want is for Django to stop selecting the 2nd or 3rd item in the pulldown and have it default to the first item like a normal pulldown. I expect that the issue has to do with declaring that the default language is 0 in the page model, but I couldn't get it to work when I removed it. -
Django doesn't see static css files
Faced a problem: django does not see static files. In particular css. Here is the project structure: settings.py (DEBUG = True): STATIC_URL = '/static/' STATICFILES_DIRS = [] STATIC_ROOT = os.path.join(BASE_DIR, "static") aboutus.html {% extends 'mainapp/base.html' %} {% load static %} <html> <head> <link type="text/css" href="{% static 'mainapp/css/aboutus.css' %}" rel="stylesheet" /> # здесь aboutus.css pycharm подчеркивает, ибо не видит </head> <body> {% block title %} О нас {% endblock %} {% block content %} <div id='div1'> <span id='span1'>▼</span> Кто мы такие?</div> <div id='div2'> 1 <span class='span2'>2</span>3 <span class='span2'>4 </span><br> 5 <br> 6 <a href="https://www.youtube.com/watch?v=OWycy6WRv7w">7</a> </div> {% endblock %} </body> </html> aboutus.css : #div1 { font-size: 20px; text-align: center; margin-top: 30px; margin-bottom : 20px } #span1 { font-size: 9pt } #div2 { box-shadow: 0 0 10px rgba(0,0,0,0.5); background-color: rgb(255,255,255); border-radius: 5px; margin-left: 10px; margin-right: 10px; line-height: 2.5; text-align: center; margin-bottom : 20px; border: 1px solid gray } .span2 { color: red } urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 'django.contrib.staticfiles' in INSTALLED_APPS is. I use mac os. -
Pycharm Community Edition - Django-Admin Command Not Recognized
I cannot start my PyCharm project via the django-admin command. The terminal doesn't recognize it. Details: 1.) I have the package installed in Python. And it is installed in my project. 2.) It seems to be installed 2 levels down from the project directory, in \venv\Scripts. But the command isn't recognized there either. Can anyone help? -
Django - What's the most secure way to pass parameters?
I'm working on an app that handles some sensitive information (API keys, etc). I have a simple question that I cannot find answers to. I have an encrypt function implemented as to not store the data in plain text. Should I be passing the variables back and forth to encrypt/decrypt between functions using return, or using request.session? They both tend to work, but what's more secure? Would it be more secure to call the function and handle the return since that would only process on the backend, or should I use session variables? -
Email not case sensitive in django allauth
How can i set an email as no case sensitive with Django Allauth? I want to save it in lowercase in database but not exist a parameter like ACCOUNT_PRESERVE_USERNAME_CASING. -
Load jquery function in vue from an external file
I am working django integrated with vuejs via webpack loader. In django's "base.html" file all static files are loaded and there is the point where vue is rendered. In vue I have a page where there is a table where all the data is loaded. In the simple html template the table and the people were via the js file that used jquery. With vuejs I can't load it. In base.html: <body class="vertical-layout vertical-menu-modern navbar-floating footer-static " data-open="click" data-menu="vertical-menu-modern" data-col=""> <div id="app"> </div> {% render_bundle 'app' %} <script src="{% static 'dashboard/js/scripts/pages/app-user-list.js' %}"></script> </body> In app-user-list.js: $(function () { ('use strict'); var dtUserTable = $('.user-list-table'), newUserSidebar = $('.new-user-modal'), newUserForm = $('.add-new-user'), select = $('.select2'), dtContact = $('.dt-contact'), statusObj = { 1: { title: 'Pending', class: 'badge-light-warning' }, 2: { title: 'Active', class: 'badge-light-success' }, 3: { title: 'Inactive', class: 'badge-light-secondary' } }; // Users List datatable if (dtUserTable.length) { dtUserTable.DataTable({ ajax: "http://127.0.0.1:8000/static/dashboard/data/user-list.json", // JSON file to add data columns: [ other... The path in the code where ajax requests leads to a file with a list of users. In this way I have loading problems because the file is loaded once if I go through vue on the page where the … -
Using different languages(frameworks) in the same web project [closed]
Please is there a way to work on a project with different languages and their frameworks. For example, I have a to build an e-commerce website with a team of three backend developers One node.js, one django and one laravel The node.js developer is to work on the products section The django developer is to work on user registration and authentication While the laravel developer is to work on the payments system Is there a way the various parts can be linked to work together on the same project? -
Create multiple website templates with django cms or any tool
Can Django be used to create a website for creating custom websites depending on the user needs? There will be more than one template and each user will have a custom url for their websites. I don't know if this can this be achieved with Django CMS. -
Django migration: got relation does not exist or relation already exists errors
I tried to port a Diango app from one server to another and change database engine from sqllite3 to postgres. After I pulled the app from github to the new server and reconfigured database settings for postgres, I got a relation not existing error when I tried to migrate as shown below. $ python manage.py migrate Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "parts" does not exist LINE 1: SELECT "parts"."type" FROM "parts" ... But after I created the table in the database and tried again, I got a relation already exists error as shown below. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, partsdb, sessions Running migrations: Applying partsdb.0001_initial...Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "parts" already exists ... So I'd get the "relation does not exist" error if I dropped the table and I'd get the "relation already exists" error if I created the table. I omitted the tracing outputs which are from Django libraries and very lengthy, but I can supply them if they may help. Thanks. -
Django message + nginx: message showing after 3 times reload !! admin login redirects back to admin login page after giving right credentials
I have built a Django application. It was working fine in the development mode. But I tried to host it in the digital ocean, Every thing worked fine, but when any error message is sent as a response, It doesn't show instantly in the front-end. Weirdly enough, If I reload three times, the error message becomes visible. my nginx configuration: listen 80; server_name <domain name>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/saadman/<project name>/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=saadman Group=www-data WorkingDirectory=/home/saadman/<projectname> ExecStart=/home/saadman/<projectname>/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ <projectname>.wsgi:application [Install] WantedBy=multi-user.target -
Django Rest Framework - drf-spectacular add extra models to schemas
I used drf-spectacular and have two questions about this module. I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this? I search a way to add custom models to Schemas but without connected this with endpoints. I see that i can add custom Schema by: """ inline_serializer( name='PasscodeResponse', fields={ 'passcode': serializers.CharField(), } ), But don't know where to put this. I wanna just see this in this Schemas like on screen: -
How to change backgrounf color of my HTML/CSS template?
I'm using this simple Boostrap template for a work and I just can't change the background color. I tried to change the background-color value over t my css file, and that has no effect at all. Tried to put the entire index file inside a div with a background-color tag, but my website is still white. Please help. -
Error in Django Model and Serializer - (1048, "Column 'dso_id' cannot be null")
I am trying to create a user profile, I feel i have everything correct but still it doesn't register. You see my codebase below, please help What i did: Models.py: class UserManager(BaseUserManager): def create_user(self, username, email, name, address,roleId,customerId,dso password=None,): if username is None: raise TypeError('User should have a userame') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username , email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('User should have a password') user=self.create_user(username,email,password,) user.is_superuser = True user.is_staff = True user.save() return user class User(models.Model): dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE) name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=True) customerId = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) @property def energy_data(self): energydata = EnergyData.objects.filter(customerId=self.customerId).first() return energydata Serializers.py: class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length = 68, min_length=6, write_only = True) class Meta: model=User fields=['email','username','password','name','address','customerId', 'dso', 'roleId'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not len(username) >= 4: raise serializers.ValidationError('Username must be morethan 4 letters or characters') return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py: class RegisterView(generics.GenericAPIView): serializer_class= … -
Is there a way to capture permission change in Django Guardian?
I would like to receive a signal after permission is changed on the object level. Django Guardian allows us to set object-level permissions. Based on the permission change, I'd like to perform some actions. How to receive a signal on object level permission change? -
Accessing custom directory under static directory in Django
I am learning Django. I know how to add use {% static "abc/xyz" %} in templates. But now I want to use something similar in views.py file. For example project->my_app->static->resources->abc.json is the file I need to access in the views.py of my_app. When I tried f = open('resources/abc.json') it didn't work. How do I do it correctly? -
Django most efficient way to count users and types
In my django project I have a user model and I want to count the different status of users. I am not sure the best way to approach as thats the top most level model so i dont think I can use annotate. I tried it but of course i on workers = get_user_model().objects.annotate( not_active_workers=Count("id", filter=Q(is_active=False, status=0)) ).annotate( active_not_complete_workers=Count("id", filter=Q(is_active=True, profile_completed=False, status=0)) ).annotate( complete_applicant_workers=Count("id", filter=Q(is_active=True, profile_completed=True, status=0)) ).annotate( former_workers=Count("id", filter=Q(is_active=False, status=2)) ).annotate( accepted_workers=Count("id", filter=Q(is_active=False, status=1)) ).filter(role=2) dict( not_active=workers[0].not_active_workers, active_not_complete=workers[0].active_not_complete_workers, complete_applicant=workers[0].complete_applicant_workers, former=workers[0].former_workers, accepted=workers[0].accepted_workers, ) The other way is count() for each filter, but it would be several queries. I think these would be pretty fast but maybe Im missing an easier way to count all queries as a dataset in 1 hit? -
authenticating normal users in django
enter image description here i am having issues with django built in forms.py which is in contrib.auth-- forms.py, i am having lot of errors in forms.py, for development i am using vscode i dont know it is isssue with vscode or what!, i am also unable to authenticate normal users after signup bcz of these errors maybe, vscode shows 162 errors in terminal, i also tried to download django from github, also reinstalled django, i dont know where is problem, i have attched screenshot. -
How do I reach a containerized django web app running in visual studio code debug mode?
After some path changes due to being a git submodule, I was able to configure a launch.json and tasks.json to get my application running in debug mode. Here are the tasks.json { "version": "2.0.0", "tasks": [ { "type": "docker-build", "label": "docker-build", "platform": "python", "dockerBuild": { "tag": "signmeasures:latest", "dockerfile": "${workspaceFolder}/signmeasures-frontend/Dockerfile", "context": "${workspaceFolder}", "pull": true } }, { "type": "docker-run", "label": "docker-run: debug", "dependsOn": [ "docker-build" ], "python": { "args": [ "runserver", "0.0.0.0:8000", "--nothreading", "--noreload" ], "file": "signmeasures-frontend/signmeasures/manage.py" } } ] } and here is the launch.json { "configurations": [ { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}/signmeasures-frontend", "remoteRoot": "/app" } ], "projectType": "django", "port": 5678, "host": "localhost" }, } ] } I'm not too familiar with setting up the debug container or docker in general, I'm still trying to learn. When I hit the debug button on the debug tab, it builds a container and then in the debug console I see this but when I try to go to localhost:8000 it does not load the web app. It shows this: I'm not sure what I need to change to be able to reach it and set breakpoints to … -
Should I override clean or validate_unique? What's the difference?
What is the difference if in models.py I had: def validate_unique(self, exclude=None): qs = KeyDefinition.objects.filter(key_name=self.key_name, developer_email=self.developer_email) print(qs) if qs: raise ValidationError ( {'key_name' : ['This Key Name already exists']} ) return super().validate_unique(exclude) vs: def clean(self): qs = KeyDefinition.objects.filter(key_name=self.key_name, developer_email=self.developer_email) print(qs) if qs: raise ValidationError ( {'key_name' : ['This Key Name already exists']} ) These seem to have no difference in the outcome. Basically, I want to make sure that each developer can't submit a key with the same name as one they already have (but two developers can have a key with the same name). I have handled this at the database level by using the unique_together option in the Meta class. -
Rabbitmq fails to boot
Rabbitmq refuses to work on my pc with the error: BOOT FAILED =========== Exception during startup: error:{case_clause,closed} rabbit_networking:record_distribution_listener/0, line 366 rabbit_networking:boot/0, line 80 rabbit:do_run_postlaunch_phase/1, line 958 {"init terminating in do_boot",{error,{case_clause,closed}}} init terminating in do_boot ({error,{case_clause,closed}}) Crash dump is being written to: c:/Users/user/AppData/Roaming/RabbitMQ/log/erl_crash.dump...done I tried downloading the erlang and rabbitmq versions that are used in the tutorial probably the new versions had different configurations or something but i was stuck only with rabbitmq 3.10.6 from the official rabbitmq website. So i tried my best to debug and tried checking the erl_crash.dump file and didn't get much from it other than random logs but got a more useful information when i checked c:/Users/user/AppData/Roaming/RabbitMQ/log/rabbit@DESKTOP-J9C9L63.log the error in the log was: [error] <0.380.0> epmd monitor failed to retrieve our port from epmd: closed But unfortunately couldn't get anything on the error online, I couldn't find the file either. I'm trying to integrate rabbitmq with django-celery,your help will be really much appreciated.