Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return http status code 401 when login with invalid credentials
How would i go about changing an django application that uses allauth so that it returns 401 response when invalid login credentials are provided? I have tried to put custom logic in a custom ModelBackend but found no way to actually modify the response status code there. I have also tried to put custom logic in a CustomAccountAdapter.authentication_failed but same issue there i found no way to change the status code. -
Please how to I fix primary key url issue in Django
I decided working of an API using Django Rest Framework and I can be able to view all the data in the endpoint but when I try to call just one of the data using a primary in the URL, I get a 404 error These are my codes. Please I need help[[[[[[Codes and the error dispayed](https://i.stack.imgur.com/yzFca.jpg)](https://i.stack.imgur.com/kbBLY.jpg)](https://i.stack.imgur.com/bSHbk.jpg)](https://i.stack.imgur.com/hjn9A.jpg)](https://i.stack.imgur.com/5E2WX.jpg)](https://i.stack.imgur.com/gdnVC.jpg) -
Django admin add form produces TypeError: __str__ returned non-string (type __proxy__)
I got the followin error message and I do not understand the issue. Further, I do not know where to start my search. TypeError at /admin/fixeddata/persondetails/add/ str returned non-string (type proxy) Request Method: GET Request URL: http://127.0.0.1:8000/admin/fixeddata/persondetails/add/ Django Version: 5.0.4 Exception Type: TypeError Exception Value: str returned non-string (type proxy) Exception Location: C:\Projects\Plattform\venv\Lib\site-packages\django\forms\models.py, line 1523, in label_from_instance Raised during: django.contrib.admin.options.add_view Python Executable: C:\Projects\Plattform\venv\Scripts\python.exe Python Version: 3.11.1 Python Path: ['c:\Projects\Plattform\project', 'C:\Python\python311.zip', 'C:\Python\DLLs', 'C:\Python\Lib', 'C:\Python', 'C:\Projects\Plattform\venv', 'C:\Projects\Plattform\venv\Lib\site-packages'] Server time: Thu, 04 Apr 2024 20:46:57 +0200 I already used str() in all my overrides of the str method of my model classes. I do not know what the "type proxy" means and when proxy is returned. In a forum entry I read something about a potential conflict with the gettext_lazy method. I use that as well in my model class. I tried to import gettext instead but that the error remains unchanged. I do not know for what type of error I am looking. It would be great if anyone could give me a hint. -
WebSocket 'Connection reset by peer, uri'
I have a Flutter app, where I'm trying to handshake with my django backend websocket. However, I'm receiving the following error: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: HttpException: Connection reset by peer, uri = http://myIP:8000/ws/chat_app/44HsUd/ Here is my Django code, where the receive method is never hit (the print statement never shows in the terminal) # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .utils import get_room class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'video_{self.room_name}' # Join room group self.room_obj = await database_sync_to_async(get_room)(unique_id=self.room_name) await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() async def disconnect(self, close_code): # Leave room group await (self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) async def receive(self, text_data): # Receive video URL from client print('test in receive') text_data_json = json.loads(text_data) video_url = text_data_json['video_url'] # Broadcast video URL to all clients in room await self.channel_layer.group_send( self.room_group_name, { 'type': 'video_url', 'video_url': video_url } ) async def video_url(self, event): # Send video URL to client video_url = event['video_url'] await self.send(text_data=json.dumps({ 'video_url': video_url })) I'm trying to make a basic video player in Flutter, here is my code there import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:web_socket_channel/io.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart'; class VideoStreamPage extends StatefulWidget { final String roomName; const VideoStreamPage({Key? key, required this.roomName}) … -
Static Files not loading Django + Azure Web App
https://github.com/EPICS-HDR/New-Code-Layout Thats the repo I have tried everything on the internet. (New to web development, need help) STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'services' /'static', ] STATIC_ROOT = os.path. join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" in urls.py: ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) standingrock.azurewebsites.net -
N+1 problems in double reverse foreign key in Django
I have N+1 problem in double reverse foreign key in Django(DRF). In models.py for example, class A(models.Model): name = models.CharField() class B(models.Model): a = models.ForeignKey(A, related_name="b") name2 = models.CharField() class C(models.Model): b = models.ForeignKey(B, related_name="c") name3 = models.CharField() Then in the middle of views.py, I called model A such as... a_obj = AA.objects.prefetch_related("b__c").get(pk=pk) And in the middle of serializers.py... def get_inform_prefetch_related(self, group): result = [] for b in group.b.all(): for c in b.c.all(): result.append({"b": b.name2, "c": c.name3}) In these codes, both b and c have N+1 problem. What should I do? -
Why Inclusion tags not working in Django?
I want to use inclusion tags to display the sidebar, but nothing is displayed. templatetags/sidebar_tags.py from ..models import Post from django import template register = template.Library() @register.inclusion_tag('blog/include/post-category.html') def post_category(): return {'posts': Post.objects.all()} post-category.html <div class="single-sidebar-widget post-category-widget"> <h4 class="category-title">Post Categories</h4> <ul class="cat-list"> {% for category in posts.categories.all %} <li> <a href="#" class="d-flex justify-content-between"> <p>{{ category.name }}</p> <p>37</p> </a> </li> {% endfor %} </ul> </div> home.html {% load sidebar_tags %} {% post_category %} I think the code is ok but I don't know why it works -
django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2
My django heroku app is building but fails during the release process with the error below. django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2.1' : filo.2.1' : file not found (0) (SQLDriverConnect)") I am using vscode in windows. I followed the CodeWithMosh process and I can run the db in dev mode on my machine. Below is a snip of the requirements.txt file. Django==5.0.3 django-filter==23.5 django-heroku==0.3.1 docopt==0.6.2 pymssql==2.2.11 pyodbc==5.1.0 sqlparse==0.4.4 virtualenv==20.25.1 My AptFile is configuration is below. `unixodbc unixodbc-dev https://packages.microsoft.com/ubuntu/22.04/prod/pool/main/m/msodbcsql18/msodbcsql18_18.3.2.1-1_arm64.deb` I have installed the MSSQL build pack and the associated UBUNTU build packs. django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/app/.apt/usr/lib/libmsodbcsql-18.3.so.2.1' : filo.2.1' : file not found (0) (SQLDriverConnect)") The first buildpack: ``https://github.com/heroku/heroku-buildpack-apt.git The second buildpack: ``https://github.com/heroku/heroku-buildpack-python.git The last buildpack: ``https://github.com/heroku-softtrends/heroku-python-pyodbc-buildpack.git Heroku support states this outside of their support (which I find... uh unfortunate). Any thoughts or suggestions are most welcome. Thx I have re-ran pipenv install pyodbc and pip freeze requirements.txt, but still have the same release fail after a successful build. remote: -----> Starting adding ODBC Driver 18 for SQL Server remote: -----> copied libmsodbcsql-18-* remote: -----> copied msodbcsqlr18.rll remote: -----> copied profile.d remote: -----> Finished adding ODBC Driver 18 for SQL Server remote: -----> Discovering process types … -
Django cookiecutter docker backups not working
I have a django cookiecutter docker project and It's on github. I have it on my windows laptop and on the company's windows server. The backups are working fine on my laptop when I do docker compose -f production.yml exec postgres backup but on the windows server the terminal seems to freeze up, it just stops and looks like nothing is happening. On my laptop it looks like this PS C:\work\*******\*******> docker compose -f production.yml exec postgres backup Backing up the 'app' database... SUCCESS: 'app' database backup 'backup_2024_04_03T19_13_30.sql.gz' has been created and placed in '/backups'. PS C:\work\*******\*******> on the windows server it looks like this. PS C:\work\*******\*******> docker compose -f production.yml exec postgres backup Also i am sure i have the same version of my project on both of them -
Origin checking failed - http://localhost:8000/ does not match any trusted origins
I have been struggling with a CORS issue with login form POST request coming from React dev server to my django backend where I am using Django's LOginView module for login requests API. These are my settings for settings.py CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ORIGINS_WHITELIST = [ 'http://localhost:3000', ] and for react I am implementing a proxy in package.json "proxy": "http://localhost:8000/", my api for user token retrieval works fine but I believe something is wrong with the CSRF verification. Kindly take a look at the title for the arisen error. Thanks. I have alreaady tried the settings reffered in documentation : https://pypi.org/project/django-cors-headers/ and someone facing the similar problem in the forum https://forum.djangoproject.com/t/origin-checking-failed-with-ssl-https/20158/13 -
Django content type showing data in `app_label: model` format in the admin dashboard
I have recently updated my application Django version from 2.2.24 to 5.0.3 after upgrading the Django I have now started getting the content_type data in this format `app_label: model` in my Django dashboard, before the update the in Django admin the content_type data was shown in this format `model`. This is the ContentType model defination, and it is imported from `django.contrib.contenttypes.models` class ContentTypeManager(BaseManager[ContentType]): def get_by_natural_key(self, app_label: str, model: str) -> ContentType: ... def get_for_model( self, model: type[Model] | Model, for_concrete_model: bool = ... ) -> ContentType: ... def get_for_models( self, *models: Any, for_concrete_models: bool = ... ) -> dict[type[Model], ContentType]: ... def get_for_id(self, id: int) -> ContentType: ... def clear_cache(self) -> None: ... class ContentType(models.Model): id: int app_label: models.CharField[Any] = ... model: models.CharField[Any] = ... objects: ClassVar[ContentTypeManager] = ... permission_set: Manager[Permission] @property def name(self) -> str: ... def model_class(self) -> type[Model] | None: ... def get_object_for_this_type(self, **kwargs: Any) -> Model: ... def get_all_objects_for_this_type(self, **kwargs: Any) -> QuerySet[Any]: ... def natural_key(self) -> tuple[str, str]: ... **As per this change my custom build functions are now breaking. Before it used to be like this And after the update(the data is a bit different but the format is changed) This is the admin … -
How do I configure i18n with django rosetta in react?
I'm writing the frontend code using react. I need to change the language on the site using Django. I don't know where to start. Should i use i18next? How can I configure if I need to use it import i18n from "i18next"; import detector from "i18next-browser-languagedetector"; import backend from "i18next-http-backend"; import { initReactI18next } from "react-i18next"; i18n .use(detector) .use(backend) .use(initReactI18next) // passes i18n down to react-i18next .init({ fallbackLng: "en", // use en if detected lng is not available saveMissing: true // send not translated keys to endpoint }); export default i18n; -
Django debug toolbar not catch query from local db
django = "4.0.8" django-debug-toolbar = "^4.3.0" drf-spectacular = "^0.26.5" Django container is connected to local database. So when call API then return response data that get from local database. But no sql query on debug toolbar panel. When I enter SQL page then only this statements are exist. SQL queries from 0 connections No SQL queries were recorded during this request. I set host.docker.internal to connect to container to local db that on host. extra_hosts: - "host.docker.internal:host-gateway" .local.env DB_ENGINE="django.contrib.gis.db.backends.postgis" DB_HOST="host.docker.internal" DEBUG=True I assigned True and False to INTERCEPT_REDIRECTS. But not worked Why django debug toolbar can not catch sql query? local_settings.py from dotenv import load_dotenv load_dotenv(".env.local") from .base_settings import * import socket DEBUG = True LOGGING["loggers"]["django"]["handlers"] = ["console", "file"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", "http://localhost:80", "http://127.0.0.1:80", "http://localhost:3000", "http://127.0.0.1:3000", "http://host.docker.internal:8000", ] CORS_ALLOW_METHODS = [ "GET", "POST", ] INTERNAL_IPS = [ "*", "127.0.0.1", "localhost", "192.168.0.1", "10.0.2.2", "host.docker.internal", ] hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips] def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "INTERCEPT_REDIRECTS": True, "SHOW_TOOLBAR_CALLBACK": show_toolbar, } if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) base_settings.py #... INSTALLED_APPS = [ "django.contrib.staticfiles", "drf_spectacular", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "real_estate", "accounts", "modu_property", "django_celery_beat", "rest_framework", "rest_framework_simplejwt", "django.contrib.gis", "debug_toolbar", "corsheaders", … -
I hosted a django project using Heroku but it keeps displaying application error. I am using gitlab
this is the error am getting this is my procfile web: gunicorn Ecom.wsgi:application and my requirements asgiref==3.7.2 attrs==23.2.0 blinker==1.7.0 certifi==2024.2.2 cffi==1.16.0 click==8.1.7 colorama==0.4.6 coverage==7.4.4 dj-database-url==2.1.0 Django==5.0.3 django-heroku==0.3.1 gunicorn==21.2.0 h11==0.14.0 idna==3.6 itsdangerous==2.1.2 Jinja2==3.1.3 MarkupSafe==2.1.5 outcome==1.3.0.post0 packaging==24.0 pillow==10.2.0 psycopg2==2.9.9 pycparser==2.21 PySocks==1.7.1 python-decouple==3.8 selenium==4.18.1 sniffio==1.3.1 sortedcontainers==2.4.0 sqlparse==0.4.4 trio==0.25.0 trio-websocket==0.11.1 typing_extensions==4.10.0 tzdata==2024.1 urllib3==2.2.1 waitress==3.0.0 Werkzeug==3.0.1 whitenoise==6.6.0 wsproto==1.2.0 and my wsgi.py """ WSGI config for Ecom project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Ecom.settings') application = get_wsgi_application() i honestly don't know what is going wrong. it keeps on stating that ecom module is not found but ecom is the name of my projectand login is the name of my app I wish for the app to run it builds and deploys the app successfully but doesnot run it -
Bulk remove many-to-many entries?
Well consider I have 1000s of users, those users are used in a many-to-many relation with "companies". Now I wish to remove all users which are "inactive" (which is the majority) from the company list. There is the trick I could use with remove: for user in User.filter(active=False): Company.customers.remove(user) However this would do also 1000s of database hits, making it really really slow. Is there a way I can do this in django? Without going to rawsql? -
django-dbbackup mediarestore causes ValueError: Cannot determine path without bucket name
I'm trying to restore my media files to my Google Cloud Storage bucket. When I run python3 manage.py mediarestore -I [FILEPATH], I get the error ValueError: Cannot determine path without bucket name. I have tried specifying my Google Cloud storage information in settings.py with: DBBACKUP_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' DBBACKUP_STORAGE_OPTIONS = { "bucket_name": "my-bucket-name", "project_id": "my-project-id", "blob_chunk_size": 1024 * 1024 } but I still get the error. Is there some other setting I need to configure? -
Creating templates and static files for Django project ( with React ) [closed]
I'm currently working on a web application using the Django Framework. In my project, I need to create several pages using React. I'm wondering whether it's better to integrate these React pages within the Django project or to develop them separately, create a build, and then include the static files within Django. I'm seeking advice on the architectural implications and the simplicity for a novice web developer. What are the pros and cons of each approach, especially considering the integration with Django and the ease of development for someone who is relatively new to web development? -
On clicking the hamburger icon on mobile devices, the navigation bar is not showing up
So, I am making a django web application, and I have designed the template to show the navigation bar when user clicks on the hamburger icon, but currently on clicking the icon, nothing is showing. HTML : <nav> <ul class="show"> <li><a href="#whatwedo">What We Do?</a></li> <li><a href="#pricing">Pricing</a></li> <li><a href="#about-page">About Us</a></li> <li><a href="#contact" class="contact-btn">Contact Us</a></li> </ul> </nav> <div class="hamburger-menu"> <div class="bar"></div> <div class="bar"></div> <div class="bar"></div> </div> CSS : @media only screen and (max-width: 768px) { nav { display: none; /* Hide the nav by default on mobile */ } .hamburger-menu { position: absolute; top: 0; right: 0; display: block; cursor: pointer; padding: 10px; z-index: 1001; /* Ensure the hamburger icon is above other elements */ } .bar { width: 25px; height: 3px; background-color: #ffffff; margin: 5px 0; } /* Show the nav links when hamburger icon is clicked */ nav ul { margin: 0; padding: 0; list-style: none; transition: transform 0.3s ease; /* Add transition property */ transform: translateY(-100%); position: fixed; top: 0; right: 0; background-color: #ffffff; border: 1px solid #ccc; padding: 10px; z-index: 1000; } nav ul.show { transform: translateY(0); /* Slide down to show menu */ } } /* Media query for larger screens (computers) */ @media only screen and … -
Django Q cannot connect to mysql
I deploy my Django, Django-Q, mysql, metabase, redis on docker, but recently, I run the services and use simpleui to change admin page, but it shows the error as follow: Traceback (most recent call last): django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection django_q | self.connect() django_q | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner django_q | return func(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect django_q | self.connection = self.get_new_connection(conn_params) django_q | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner django_q | return func(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection django_q | connection = Database.connect(**conn_params) django_q | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 121, in Connect django_q | return Connection(*args, **kwargs) django_q | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 193, in __init__ django_q | super().__init__(*args, **kwargs2) django_q | MySQLdb.OperationalError: (2002, "Can't connect to server on 'mysql' (115)") django_q | django_q | The above exception was the direct cause of the following exception: django_q | django_q | Traceback (most recent call last): django_q | File "/app/manage.py", line 22, in <module> django_q | main() django_q | File "/app/manage.py", line 18, in main django_q | execute_from_command_line(sys.argv) django_q | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line django_q | utility.execute() django_q | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute django_q … -
How to properly set my setting.py file when using django-mongoengine with Django Rest Framework?
I'm trying to make my first migration using django and django-mongoengine. I'm rather new to the topic. When i launch my first python manage.py makemigrations, I get the following error: AttributeError: module 'mongoengine' has no attribute 'mongo_admin' ... ModuleNotFoundError: No module named 'mongoengine.mongo_admin' Here is my INSTALLED_APPS list INSTALLED_APPS when I comment #'mongoengine.mongo_admin' I get the following error: Error when commenting mongoengine.mongo_admin Here is my pip list result: (venv) PS C:\Users\sabat\Documents\Diginamic\Stage\CampingBack\Camping\WebCamping> pip list Package Version ---------------------------------- -------- asgiref 3.8.1 blinker 1.7.0 build 1.2.1 certifi 2024.2.2 charset-normalizer 3.3.2 click 8.1.7 colorama 0.4.6 Django 3.0 django-admin-honeypot-updated-2021 1.2.0 django-axes 5.27.0 django-browserid 2.0.2 django-classy-tags 3.0.1 django-cors-headers 3.11.0 django-cors-middleware 1.5.0 django-environ 0.11.2 django-filter 21.1 django-ipware 4.0.2 django-missing 1.1.0 django-mongo-auth 0.1.3 django-mongoengine 0.4.6 django-sekizai 3.0.1 djangorestframework 3.15.1 dnspython 2.6.1 environ 1.0 idna 3.6 Markdown 3.6 mongoengine 0.27.0 oauthlib 3.2.2 packaging 24.0 panda 0.3.1 pip 23.2.1 pip-tools 7.4.1 pymongo 4.6.3 pyproject_hooks 1.0.0 pytz 2024.1 requests 2.31.0 requests-oauthlib 1.3.1 setuptools 65.5.0 sqlparse 0.4.4 tweepy 4.14.0 urllib3 2.2.1 wheel 0.43.0 I haven't find any informations on this topic in the doc of mongoengine. Should I use a less recent version of django or other version of mongoengine and/or django-mongo-auth and/or django-mongoengine? Or is anybody has a working project with … -
Django Testing: Error handling in setUpTestData
I want to write a test for a data-loading command, which creates a large number (thousands) of objects variously related by foreign keys. There are two ways I might structure it Invoke the management commands in setUpTestData, and then write data consistency tests as ordinary tests Write one large test method to run the management commands, and then subtests to check the data consistency subtests are a Python unittest feature which the Django test runner inherits: with self.subTest("Subtest Foo"): self.assertFalse( True) # FAIL message includes [Subtest Foo] with self.subTest("Subtest Bar"): self.assertFalse( True) # and failure doesn't stop the next subtest from running Is there any particular reason to prefer one over the other? Does setUpTestData wrap the entire class in a DB transaction, so the tests DB is left unchanged should it fail here rather than inside one or more of the tests? Incidentally, I've never seen any reference to how to write a test that will never run unless the ./manage.py test ... command explicitly asks for it. So this might be useful to somebody: from unittest import skipIf import sys @skipIf( not 'test123' in sys.argv, "Runs only with --tag test123") @tag('test123') class Test03( TestCase): ... will run Test03 … -
query in many to many field order by first related object
in django i want to query in a many to many field that ordered by first related object. that means the queryset have to serach in the objects in the first location of many to many objects then others. as a simple incorrect sample i want to get objects like this: queryset = Practitioner.objects.filter(practices__0__city__slug='toronto') queryset += Practitioner.objects.filter(practices__other__except__0__city__slug='toronto') Note: practices is a ManyToManyField of Practice model in Practitioner model -
"GET / HTTP/1.1" 400 143 "-" "Render/1.0"
When I try to deploy Django to render, the following characters are displayed and I cannot deploy. ==> Detected service running on port 10000 ==> Docs on specifying a port: https://render.com/docs/web-services#port-detection 10.209.24.8 - - [04/Apr/2024:19:06:48 +0900] "GET / HTTP/1.1" 400 143 "-" "Render/1.0"[![enter image description here][1]][1] When I asked chatgpt, I was told that ALLOWED_HOSTS may not be set, but I think ALLOWED_HOSTS is set properly. from pathlib import Path from django.core.management.utils import get_random_secret_key import dj_database_url from dotenv import load_dotenv import os SECRET_KEY = os.environ.get('SECRET_KEY', 'xxxxxxxxxxxxxx') ALLOWED_HOSTS = ['10.209.25.170', 'django-render-xxx.onrender.com'] -
Django 'When' object is not iterable
I'm using django-filter to show work-hour of employs. models.py: ... class Attendance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Attendances") day = models.DateField() start_time = models.TimeField() end_time = models.TimeField() is_confirmed = models.BooleanField() task = models.ForeignKey(Tasks, on_delete=models.CASCADE) ... filter.py: class WorkhourFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(WorkhourFilter, self).__init__(*args, **kwargs) start_date = ... end_date = ... self.queryset = self.Meta.model.objects.filter(user=self.request.user, day__gte=start_date, day__lte=end_date).values('task__project__title', 'task__project').annotate( raw_work_hour=Sum(F('end_time') - F('start_time'), ), confirmed_work_hour=Sum(Case(When(is_verified=1, then=F('end_time') - F('start_time'))))).order_by('task__project') I get 'When' object is not iterable error. confirmed_work_hour has problem but the raw_work_hour alone is not a problem. This query is working well in get_queryset() of corresponding View but when I trying to apply filters it'll break. trace : Django Version: 4.2.5 Python Version: 3.9.13 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'crispy_forms', 'crispy_bootstrap5', 'django_tables2', 'django_htmx', 'django_filters', 'jalali_date', 'ckeditor', 'ckeditor_uploader', 'guardian', 'django_cascading_dropdown_widget', 'dashboard.apps.DashboardsConfig', 'auth.apps.AuthConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_htmx.middleware.HtmxMiddleware'] Traceback (most recent call last): File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Python\DjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 438, in dispatch return super(StaffuserRequiredMixin, self).dispatch( File "D:\Python\DjangoTest\venv\lib\site-packages\braces\views\_access.py", line 375, in … -
How to display the uuid field of my serializer as a string in a get request with django restframework
Here is my serializer class AgenceSerializer(serializers.Serializer): uuid = serializers.UUIDField(format='hex',allow_null=True,required=False) <------- p1 = serializers.CharField(max_length=50,required=True) p2 = serializers.CharField(max_length=50,required=True) views.py @api_view(["POST"]) def details_agence(request): if request.method == "POST": serializer = AgenceUUIDSerializer(data=request.data) if serializer.is_valid(): agence_repr = serializer.agence_details(data=request.data) serializer = AgenceSerializer(agence_repr) print(serializer) return Response(serializer.data,status=status.HTTP_200_OK) <--------- ... a print on the serializer gives me the following: AgenceSerializer({'uudi': 'A75DF036-6C16-4311-9825-22B1295D8A26', 'p1': 'Ozangue', ...}): uuid = UUIDField(allow_null=True, format='hex', required=False) ... But when I display the data, in the response, the uuid field is always null How to solve this problem ?