Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the _allowed_methods() function in django APIView return all http methods even though only GET is implemented?
I have a view being inherited by APIView and I have only implemented the GET method in it. class MyView(APIView): def get(self, request, id): # do something But when I call ClassInstance._allowed_methods() I get list of all the HTTP methods even though they are not implemented. Is there a way to only get the methods that are actually allowed in that class? -
TemplateDoesNotExist at /members/login/ registration/login.html
There are two similar questions on stackoverflow but they didn't help. I guess I got myself into trouble because I did a lot of copy and past from other projects. please help my settings.py: INSTALLED_APPS = [ ... 'core', 'members', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_URL = 'members:login' LOGIN_REDIRECT_URL = '/' # Default landing page after login LOGOUT_REDIRECT_URL = '/' # Default landing page after logout # Email verification EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "nadirspam3@gmail.com" EMAIL_HOST_PASSWORD = "xwie mpdm tmyu lyiw" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "nadirspam3@gmail.com" my members app views file: def login_user(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) # Redirect to a success page. return redirect('home') else: messages.success(request, 'Wrong username or password. Try again ..') return redirect('members:login') else: return render(request, 'members/login.html', {}) # so we can reference the user model as User instead of CustomUser User = get_user_model() ... my members app urls file: from . import views app_name = 'members' urlpatterns = [ path('login_user', views.login_user, name='login'), path('signup/', … -
Django + FactoryBoy -> Postgres not converting datetime to utc correctly
Okay, this is a weird one. I've got a Django model that I'm writing to Postgres via FactoryBoy for testing. contract = ContractFactory( effective_date=datetime.datetime(2023, 1, 1, tzinfo=pytz.timezone('US/Central')) ) I'm in US/Central, and I expect the database to store the object in UTC. The datetime in Postgres should be 2023-01-01 06:00:00 UTC since the difference between timezones is 6 hours. If I fetch the object back and print the date, it's wrong! 2023-01-01 05:51:00+00:00 If I fetch it from Postgres directly, it's also wrong: 2023-01-01 05:51:00.000000 +00:00 I checked the raw time in the database and it's correct. Postgres is running in a Docker container, and if I do a select now() the time is just fine in UTC. Where could this be coming from? -
Django Deployment on Azure: 504 Timeout and ROOT_URLCONF Error
I'm deploying a Django app to Azure using GitHub Actions, but encountering a 504 Gateway Timeout on the first request and an AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' error afterwards. I've followed the documentation and confirmed the ROOT_URLCONF setting in my settings.py. The app also downloads a machine learning model from Azure Blob Storage during startup. wsgi.py: import os from django.core.wsgi import get_wsgi_application settings_module = 'FakeNewsDetectorAPI.deployment' if 'WEBSITE_HOSTNAME' in os.environ else 'FakeNewsDetectorAPI.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module) print("Before get_wsgi_application()") application = get_wsgi_application() print("After get_wsgi_application()") settings.py: import os from pathlib import Path print("Loading settings.py") BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['fake-news-app22.azurewebsites.net','localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'django.contrib.auth', 'rest_framework', 'core.livenews', 'core.newsquiz', 'corsheaders', ] # Template configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', ], }, }, ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', # Azure Blob Storage Settings AZURE_STORAGE_CONNECTION_STRING = os.environ.get('AZURE_STORAGE_CONNECTION_STRING') AZURE_STORAGE_CONTAINER_NAME = 'models' MODEL_BLOB_NAME = 'model_1_5_2.pkl' LOCAL_MODEL_PATH = os.path.join(BASE_DIR, 'models', 'model_1_5_2.pkl') # Database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CORS_ALLOWED_ORIGINS = [ "http://localhost:19000", "http://127.0.0.1:8000", "https://fake-news-app22.azurewebsites.net", ] CORS_ALLOW_CREDENTIALS = True REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', … -
django.db.utils.ProgrammingError: (1146, "Table 'test_db.sensori' doesn't exist")
i have this problem when i run my testcase with django and mysql. when i run manage.py test i've got this error. Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_sensor_list_view (gestioneSensori.tests.ViewsTest.test_sensor_list_view) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute res = self._query(mogrified_query) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query db.query(q) File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\MySQLdb\connections.py", line 265, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'test_db.sensori' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\gestioneSensori\tests.py", line 10, in test_sensor_list_view sensore1 = Sensori.objects.create(id=1, tipo="Temperature", descrizione='desc', accuratezza=.0, precisione=.0, temperaturamin=0.0, temperaturamax=10.0, tolleranza=.1, tensioneesercizio=12.0, sensibilita=.2) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\query.py", line 679, in create obj.save(force_insert=True, using=self.db) File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 892, in save self.save_base( File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 998, in save_base updated = self._save_table( ^^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 1161, in _save_table results = self._do_insert( ^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\base.py", line 1202, in _do_insert return manager._insert( ^^^^^^^^^^^^^^^^ File "C:\Users\faboz\OneDrive\Desktop\ESAME_TWAI\Codice\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … -
Callable default on unique field will not generate unique values upon migrating
Using Django/DRF to create a CRUD api I'm trying to use the RandomUUID to create a UUID from Postgres: from django.db import models from django.contrib.postgres.functions import RandomUUID class Year(models.Model): year_id = models.UUIDField( primary_key=True, default=RandomUUID, editable=False) When I run python manage.py makemigrations It gives me this error: Callable default on unique field year.year_id will not generate unique values upon migrating What am I doing wrong? I want Django ORM to tell Postgres to create the UUID. I don't want to use Python's uuid module. -
How I can let Django and FastAPI share the context (user) with the orm requests?
So I am writing an app with NiceGUI that is built on FastAPI and with Django. Right now I have no problem in the FastAPI to call the Django ORM in async to save in the database etc. The problem is that I am trying to share to the ORM requests that I do also the context in this way knows who is the user doing the various requests. I have implemented the login manually with aauthenticate and works (I save a token in the user model for the auth) but if I call a model like "Product" doens't have the request.context so I can't use https://github.com/jazzband/django-simple-history/ to save the author of the changes. I was thinking to create a custom auth middleware but how I can be sure that the ORM requests I will do will get that context? Another test I was doing was to create a RequestFactory and create a HTTPRequest manually with the session and login at the end but I have the same doubts. Another solution could be create a custom history and not use that package but I have some doubts that the issue will happen again for another reason. -
NoReverseMatch at /cart/
As I delete the item from the cart from the minus button the following error occurs Reverse for 'remove_cart' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart/(?P<product_id>[0-9]+)/(?P<cart_item_id>[0-9]+)/$'] how can I fix it views.py of carts app def remove_cart(request, product_id, cart_item_id): cart = Cart.objects.get(cart_id = _cart_id(request)) product = get_object_or_404(Product, id=product_id) try: cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id) if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() else: cart_item.delete() except: pass return redirect('cart') urls.py file of the carts app path('remove_cart/<int:product_id>/<int:cart_item_id>/', views.remove_cart, name='remove_cart'), Cart.html file <div class="input-group-prepend"> <a href="{% url 'remove_cart' cart_item.product.id, cart_item.id %}" class="btn btn-light" type="button" id="button-plus"> <i class="fa fa-minus"></i> </a> </div> -
How to redirect a user to a mobile app (without browser) using Django (Universal Link / App Link) with .well-known configuration?
I am working on a Django-based web application, and I need to implement a feature where users are redirected to a mobile app directly (without using a browser) when they visit a specific URL. I want to use Universal Links (for iOS) or App Links (for Android) and ensure the redirect happens seamlessly. My setup: URL pattern: I am using a URL like /api/app/login/str:session_token/. Mobile app URL: I want to redirect users to a custom scheme URL like myapp://path/to/page/. Current view: This is my view that tries to handle the redirection: from django.http import HttpResponseRedirect from django.views import View class MobileRedirectView(View): def get(self, request, *args, **kwargs): # Custom mobile app URL (Universal Link for iOS or App Link for Android) mobile_app_url = "myapp://path/to/page/" # Redirecting to the mobile app return HttpResponseRedirect(mobile_app_url) The problem: When trying to redirect to the mobile app URL using the custom scheme (myapp://), I get this error: django.core.exceptions.DisallowedRedirect: Unsafe redirect to URL with protocol 'myapp'. I know that Django by default only allows redirects to http:// or https:// URLs, but I need to allow custom schemes like myapp://. Goal: I want the redirection to happen without using a browser (directly into the mobile app), and I … -
Django request.POST is empty
Im using django, allauth and dj-rest-auth. I'm implementing apple sign in. There is an issue with apple that I need multiple client_id's configured, its because you need a different one for ios en android/web. The issue is discussed here: https://github.com/pennersr/django-allauth/issues/2718 With also some solutions. Anyway, my question is not about that issue. I'm trying to implement a solution but django is not working like I expect it to. The issue is that that I cant access request.POST data. Which I think should be possible. # We add client_id when we make the post request, and we use it to filter for it def list_apps(self, request, provider=None, client_id=None): print(request.POST) --> returns empty dict # print(request.body) --> error # print(request.data) --> error assert False print(request.POST.get('client_id')) apps = super().list_apps(request=request, provider=provider, client_id=client_id) return apps request.body gives the error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream request.data gives the error: AttributeError: 'WSGIRequest' object has no attribute 'data' I would expect that I can access at least one of request.body, request.data or request.POST. Or else how can I access my posted data? -
Django admin - using dja have a style problem
i have an issue in the style admin of Django, when i enter on the web admin it show this: it show a broken style, with black lines I have this in my user_settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = '/srv/media' MEDIA_URL = 'media/' The version of python is 3.12.3 and Django is 4.2 Any suggestions on how to resolve this problem would be greatly appreciated. -
CSRF Failed: CSRF token missing
I am writing my code in django python, Here is my view.py @csrf_exempt @api_view(['POST']) def Userlogin1(request): print('login working') username = request.data.get('username') password = request.data.get('password') user = authenticate(request=request._request, username = username, password = password) if user is not None: login(request._request, user) return Response({'message': 'login successful.'}, status=status.HTTP_200_OK) return Response({'error': 'Invalid credentials.', 'user':user, 'username':username, 'password':password}, status=status.HTTP_401_UNAUTHORIZED) when i run this on the postman, on first POST request, postman returning a correct response <'message': 'login successful.> but on second and further hit, post man throwing 403 error with this message { "detail": "CSRF Failed: CSRF token missing." } after removing the cookies from postman, it can run once but shows again same issue I disabled the csrf token added CSRF_TRUSTED_ORIGINS created custom -
Python project wrongly linked to Django
I'm pretty new with Django and I'm making a Flight Searching App with the Amadeus API. I've made it so, that it creates a .csv file with the cheapest flights from one destination to another. I now want to create a web application that lets the user enter cities and dates and displays the .csv file. I've made the HTML template but whenever I click on "Search" I get thrown a 404 Error. I think there is an error with urls.py or views.py but can't seem to figure it out. This is my views.py from django.shortcuts import render import requests import pandas as pd def search_flights(request): if request.method == 'POST': origen = request.POST.get('origen') destino = request.POST.get('destino') fecha_ida = request.POST.get('fecha_ida') fecha_regreso = request.POST.get('fecha_regreso') params = { "originLocationCode": origen, "destinationLocationCode": destino, "departureDate": fecha_ida, "returnDate": fecha_regreso, "adults": 1, "max": 7 } url = "https://test.api.amadeus.com/v2/shopping/flight-offers" access_token = "*********************" headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(url, headers=headers, params=params) if response.status_code == 200: resultados = response.json().get("data", []) vuelos_data = [] for vuelo in resultados: price = vuelo.get("price", {}).get("total", "N/A") currency = vuelo.get("price", {}).get("currency", "N/A") for itinerary in vuelo.get("itineraries", []): for segment in itinerary.get("segments", []): departure = segment.get("departure", {}) arrival = segment.get("arrival", {}) carrier_code … -
How to use ChoiceField and ModelChoiceField with allauth Templates?
Based on the default allauth Templates I want to build a Custom SignUp Form which also includes ChoiceField and ModelChoiceField. Therefore I did the following adjustments: accounts/models.py class Country(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class CustomUser(AbstractUser): SALUTATION = ( ('m', _('Mr')), ('f', _('Mrs')), ) salutation = models.CharField( max_length=1, choices=SALUTATION, blank=True, null=True ) country = models.ForeignKey( Country, on_delete=models.PROTECT, verbose_name=_('Country'), blank=True, null=True ) accounts/forms.py class CustomSignupForm(forms.Form): salutation = forms.ChoiceField(widget=Select, choices=CustomUser.SALUTATION, initial=CustomUser.SALUTATION) country = forms.ModelChoiceField(queryset=Country.objects.all(), initial=Country.objects.all()) templates/allauth/elements/field.html {% load allauth %} {% if attrs.type == "select" %} <select name="{{ attrs.name }}" id="{{ attrs.id }}" class="form-select mb-3"> {% for option in attrs.value %} <option value="{% if option.0 %}{{ option.0 }}{% else %}{{ option.id }}{% endif %}"> {% if option.1 %} {{ option.1 }} {% else %} {{ option }} {% endif %} </option> {% endfor %} </select> {% elif attrs.type == "checkbox" or attrs.type == "radio" %} ... Options only get populated to attrs.value when passing 'initial' parameter in the form. Shouldn't this be provided by 'choices' or 'queryset' parameter instead? Is there an option to get the values from attrs object in a different way? -
How to handle teardown using django-tenant?
I'm using django-tenant and having trouble when i try to create my tests. I had to create a setup_tenant class to create a teardown before testing, because to access the restaurant table, I had to create the tenant upstream. However, when my tests finish successfully, I get an error during teardown: ERROR restaurants/tests.py::RestaurantTests::test_update_restaurant - django.db.utils.ProgrammingError: relation "restaurants_restaurant" does not exist This is the full error: restaurants/tests.py::RestaurantTests::test_update_restaurant PASSED [100%] restaurants/tests.py::RestaurantTests::test_update_restaurant ERROR [100%] ======================================================================================================= ERRORS ======================================================================================================= ____________________________________________________________________________ ERROR at teardown of RestaurantTests.test_update_restaurant _____________________________________________________________________________ self = <django.db.backends.utils.CursorWrapper object at 0x108b084a0> sql = 'SELECT "restaurants_restaurant"."id", "restaurants_restaurant"."name", "restaurants_restaurant"."owner_id", "restaura... "restaurants_restaurant"."tenant_id" FROM "restaurants_restaurant" WHERE "restaurants_restaurant"."tenant_id" IN (%s)' params = (1,), ignored_wrapper_args = (False, {'connection': <DatabaseWrapper vendor='postgresql' alias='default'>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x108b084a0>}) def _execute(self, sql, params, *ignored_wrapper_args): # Raise a warning during app initialization (stored_app_configs is only # ever set during testing). if not apps.ready and not apps.stored_app_configs: warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning) self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) This is my Restaurant model: from customer.models import CustomerTenant class Restaurant(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, related_name="restaurants", on_delete=models.CASCADE) description = models.TextField(blank=True, default="") created_at = models.DateTimeField(auto_now_add=True) tenant = models.ForeignKey(CustomerTenant, on_delete=models.CASCADE, related_name="restaurants") def __str__(self): return self.name` … -
nginx gives django static status 200 inside docker, but it is not shown
I have a static directory in my nginx container and when I go to http://localhost/admin it gives me nginx | 1.1.1.1 - - [10/Dec/2024:12:41:17 +0000] "GET /static/admin/css/base.css HTTP/1.1" 200 21544 "http://localhost/admin/login/? next=/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" but it doesn’t show up, what’s the error? P.S in developer mode in Networks I see loaded static, I cleared the cache, in my html there is {% load static %} docker-compose: django: container_name: django build: context: django command: gunicorn -w 4 --bind 0.0.0.0:9000 src.wsgi:application working_dir: /django/src volumes: - ./django:/django - static_volume:/django/src/static env_file: - django/.env depends_on: - django_postgres ports: - "9000:9000" nginx: image: nginx:latest container_name: nginx ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - static_volume:/static depends_on: - django environment: - NGINX_LOGGING_STDOUT=true volumes: static_volume: nginx.conf events { worker_connections 1024; } http { server { listen 80; server_name localhost; location /static/ { alias /static/; access_log /dev/stdout; error_log /dev/stderr debug; } location /favicon.ico { access_log off; return 204; } location ~* \.map$ { log_not_found off; access_log off; } location / { proxy_pass http://django:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_log /var/log/nginx/error.log debug; } } settings.py DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = … -
How to get the method name with the url using django.urls.get_resolver()
I am getting these urls with django's get_resolver() function for a class: ^api/asset_management/^^get_assets/$ ^api/asset_management/^^get_assets\.(?P<format>[a-z0-9]+)/?$ ^api/asset_management/^^get_assets/(?P<pk>[^/.]+)/$ ^api/asset_management/^^get_assets/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ I also want the name of the method where each of these url is redirected e.g. Get, Post etc. The class is a simple ModelViewSet and is registered by the DefaultRouter. -
Django socket on Digitalocean, path not found
INSTALLED_APPS = [ 'daphne', 'channels', ] ASGI_APPLICATION = 'HungerPlace.asgi.application' CHANNEL_LAYERS = { 'default': { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [REDIS_URL], }, }, } consumers.py class OrderConsumer(AsyncWebsocketConsumer): # Cambiato a AsyncWebsocketConsumer async def connect(self): user = self.scope["user"] struttura_id = await self.get_user_structure_id(user) if user.is_authenticated and struttura_id: self.group_name = f"orders_{struttura_id}" await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() else: await self.close() async def disconnect(self, close_code): if hasattr(self, "group_name"): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def send_order(self, event): if "data" in event: # await self.send(event["data"]) await self.send(text_data=json.dumps(event["data"])) else: print(f"Received event without 'data': {event}") async def receive(self, text_data): # Log per il debug await self.send(text_data="Message received") @sync_to_async def get_user_structure_id(self, user): """Esegue operazioni sincrone in un thread separato.""" if user.is_authenticated and user.profilo.strut: return user.profilo.strut.id return None routing.py from django.urls import path, re_path from .consumers import OrderConsumer websocket_urlpatterns = [ path('ws/orders/', OrderConsumer.as_asgi()), ] asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HungerPlace.settings') django_asgi_app = get_asgi_application() from login.routing import websocket_urlpatterns application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) the project is using django-allauth, channel, daphne. But the main think is when I am on localhost it does work. when I deploy on digitalocean (it is not a droplet, it is an app), it does not find the url Not Found: /ws/orders/ I am trying a … -
Is there a solution to type hint a django annotation?
I have a django project which I am trying to type and add type checking through mypy. I want to use django annotations to get more informations about an object. This operation adds properties to a class already declared. The package django-stubs already provides a typing class WithAnnotations that should do the work but it doesn't. To be clear, I simply want this code to pass mypy from django.db import models class User(models.Model): first_name: models.CharField() last_name: models.CharField() class Team(models.Model): users: models.ManyToManyField(User) class House(models.Model): inhabitants: models.ManyToManyField(User) users = User.objects.all() for user in users: print(user.first_name) users_with_teams = Users.objects.all().annotate(teams_ids=ArrayAgg(...)) users_with_teams_and_houses = users_with_teams.annotate(houses_ids=ArrayAgg(...)) for user in users_with_teams: print(user.first_name) print(user.teams_ids) print(user.houses_ids) If I try to run it I get errors object User has no attribute teams_ids or object User has no attribute houses_ids I thought it would be nice to have it in functions: from typing import TypeVar T = TypeVar("T") def annotate_teams(query: QuerySet[T]) -> QuerySet[SomethingElseButWhat]: return query.annotate(teams_ids=ArrayAgg(...)) but I don't know which type my function should return. Does any of you know if what I am looking for is possible ? -
What's the proper way to conclude the OAuth2 flow in Django?
To keep the story short, I've acquired all the necessary tokens from Google using the "auth code" flow. So currently, I have the following tokens at my disposal: 1. access_token 2. refresh_token 3. id_token 4. verified JWT token The next step is to log in the user using the provided login() method from django.contrib.auth. This creates a sessionId which is then used to "verify" that a user is logged in. In my current development setup, I'm just using the email from the JWT token to create the session: from django.contrib.auth import login from django.contrib.auth.models import User def login_provider(request): # 1. Get the user info from JWT token (assume I have it) user_obj = jwt_token.user # 2. Create a Django user instance user, created = User.objects.get_or_create(email=user_obj.email) # 3. Log the user in login(request, user) # 4. Redirect the user somewhere else return redirect("somewhere-else/") I've taken all the necessary steps to ensure the Google OAuth2 flow part is secure but am I correct in assuming that this way of logging the user in isn't secure since I'm basically using just the users email? What's the correct way to do this? -
Logs not getting sent to Datadog when running Django shell inside a container
The logs that are created by the code running inside the container do get sent to Datadog, but when I'm in a shell session inside the container those logs get outputted in the terminal, but not sent to Datadog. Therefore, once I leave the session (if I don't copy and paste the logs into a file), they are forever lost. TL;DR; Datadog Agent runs inside the container, but not inside the shell session inside the container How can I make it so that the logs produced inside the shell session also get sent to Datadog ? -
How to add element in Django QuerySet?
I have model Report and GroupReport. They have many-to-many relation. I can easily get QuerySet[GroupReport] for all GroupReport instance: Group Name 1: Report Name 1 Report Name 2 Group Name 2: Report Name 2 Report Name 10 ... and etc. But i need to add entry "Total Reports" to QuerySet[GroupReport]: Group All reports: Report Name 1 Report Name 2 Report Name 5 ... and another reports from QuerySet[Report] I can't store group "Total Reports" in database because using object permissions for QuerySets. It is necessary to generate the group dynamically. My Serializer expect correct queryset. How can i do this? I tried to do it something like this: def get_queryset(self): groups = get_objects_for_user( user=self.request.user, perms=view_reportgroup, klass=ReportGroup.actived_objects, accept_global_perms=False ) reports = get_objects_for_user( user=self.request.user, perms=view_report, klass=Report.actived_objects, accept_global_perms=False ) total = ReportStorage(id=None, name='Total Reports') total.reports.set( Report.actived_objects.filter( Q(id__in=reports) | Q(groups__in=groups) ).distinct() ) return (groups | total).prefetch_related( Prefetch( 'reports', queryset=ReportStorage.prefetch_related( Prefetch( 'reportstorage', queryset=super().get_queryset() ) ) ) ) But got expected error: "needs to have a value for field 'id' bla-bla..." for total.reports.set. I was also thinking about adding ReportStorage to groups._result_cache. But I don't understand how it should look. Maybe there are more correct ways such as custom SQL, converting QuerySet to List? -
Kafka consumer is missing messages during deployment
My consumers are inherited from the BasicKafkaConsumerV2. During deployments when the pods are rotating I am missing few messages which is visible from the offsets printed after the manual commit(). Kafka is not supposed to miss messages if not committed. What could be the problem here. run command: - name: order-consumer image: KUSTOMIZE_PRIMARY imagePullPolicy: Always command: [ # Invoking wait for pgbouncer script "/wait-for.sh", "localhost:6432", "-s", "-t", "30", "--", # Starting main process "ddtrace-run", "python", "manage.py", "run_order-consumer", ] Consumer: class BasicKafkaConsumerV2: group_id = None # str consumer_name = None # str newrelic_application = None topic_handlers = {} # dict DB_EXCEPTION_RETRY_TIMEOUT = 5 # seconds DLQ_TOPIC = None def __init__(self, latest_offset=False): """Inits the Consumer and subscribes to the topics""" self.consumer = KafkaConsumer( bootstrap_servers=["broker1", "broker2"], group_id=self.group_id, enable_auto_commit=False, auto_offset_reset="latest", ) self.topics_list = list(self.topic_handlers.keys()) self.consumer.subscribe(self.topics_list) self.newrelic_application = newrelic.agent.application() logger.info( f"{[self.consumer_name]} subscribed to {self.topics_list} with auto_offset_reset {self.auto_offset_reset}" ) def message_handler_wrapped( self, topic: str, kafka_msg_value: bytes, headers: dict, consumed_message=None, ): """Processes the message Also handles any DB exceptions by retrying the event after a period """ with tracer.trace( settings.DD_KAFKA_RESOURCE_NAME, service=settings.DD_SERVICE, resource=self.group_id, span_type="consumer", ) as span: try: json_data = json.loads(kafka_msg_value) dict_headers = convert_tuple_to_dict(headers) span.set_tag("topic", topic) span.set_tag("event", self.get_event_name(json_data)) self.message_handler(topic, json_data, dict_headers) except (InterfaceError, OperationalError) as e: """Sleep for … -
Create non existing tag with Django-select2
I am using django-select2 to autocomplete a tag field on a model. I would like to let user write any tag in the field, and create it if the tag doesn't exists... # models.py class Version(models.Model): ... tags = models.ManyToManyField(Tag, blank=True) class VersionTagWidget(s2forms.ModelSelect2TagWidget): search_fields = [ "nom__icontains", ] class VersionEditViewForm(forms.ModelForm): def __init__(self, *args, **kwargs): ... class Meta: model = Version widgets = { "tags": VersionTagWidget, } I can autocomplete value (and select in a dynamic dropdown), but if type in a non-existing (in my example, I entered 'DoesNotExist') value and submit the form, I get : Exception Value: Field 'id' expected a number but got 'DoesNotExist'. I tried a lot of things to solve the pb.... But no clue here... -
Safely Storing Passwords and Database Credentials in Django [closed]
Does anyone here have experience with Django? How can I safely store my passwords, database credentials, and other sensitive information in settings.py? I found it using cryptography but wanted to hear more ideas.. Someone Can help me?