Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
504 Gateway Timeout in Production for Django API Endpoint with Meta Products Feed API, but Works Locally
I'm working on a Django API that integrates with the Meta API for WhatsApp product feeds. This endpoint works perfectly on my local machine, but when I deploy it to production, it returns a 504 Gateway Timeout error. Details: Local Request (Works): curl -X POST http://127.0.0.1:8000/api/whatseat/save-changes/ -d "business_id=2" Production Request (504 Gateway Timeout): curl -X POST https://<production-url>/api/whatseat/save-changes/ -H "Authorization: Token <token>" -d '{"business_id": 2}' Key Observations: Error happens only in production—locally, the endpoint works fine. When this endpoint is called without the necessary WhatsApp data, it correctly returns a prompt to complete settings. So, the problem seems to occur during an external API request to the Meta (WhatsApp) API. def post(self, request): business_id = request.data.get('business_id') try: whatsapp_business = WhatsApp.objects.get(business=business_id) except ObjectDoesNotExist: return Response({"message": "Complete WhatsApp setup in settings"}, status=400) access_token = whatsapp_business.access_token product_catalog_id = whatsapp_business.catalog_id if not all([access_token, product_catalog_id]): return Response({"error": "Missing Access Token or Catalog ID"}, status=400) # External API request (seems to be the timeout issue in production) try: product_feed_data = request.build_absolute_uri(reverse('get-product-feeds')) response = requests.get(product_feed_data, params={ 'access_token': access_token, 'product_catalog_id': product_catalog_id }) response.raise_for_status() except requests.RequestException as e: return Response({'error': str(e)}, status=500) # Other logic... (contains another call to graph api for uploading the new data feed) Troubleshooting Attempts: Local … -
Show product name in template django
I want to show all of the user orders in its panel so, I have following models: this is my product model in django and in my order model I have productfk field that is id of user product. class Product(models.Model): id= models.IntegerField(primary_key=True) activedate = models.DateField() name= models.CharField(max_length=256) description = models.TextField() #following u can set user owner for this row #owner =models.ForeignKey(to=User,on_delete=models.CASCADE) category = models.CharField(max_length=256) unit =models.CharField(max_length=50) active = models.BooleanField(default=False) unitprice = models.DecimalField(max_digits=18, decimal_places=0) quantity = models.FloatField() minorder = models.FloatField() maxorder = models.FloatField() readytopay = models.BooleanField(default=False) showquantity = models.BooleanField(default=False) lastupdate = models.DateField() def __str__(self): return self.name and folloring is my order model: class Orders(models.Model): id = models.IntegerField(primary_key=True) customerfk = models.ForeignKey(to=User,on_delete=models.CASCADE) oxygenid = models.IntegerField() financialfk = models.IntegerField() orderdate = models.DateTimeField() productfk = models.IntegerField() unit = models.CharField(max_length=50) quantity = models.FloatField() unitprice = models.DecimalField(max_digits=18, decimal_places=0) discount = models.DecimalField(max_digits=18, decimal_places=0) totalprice = models.DecimalField(max_digits=18, decimal_places=0) onlinepayment = models.DecimalField(max_digits=18, decimal_places=0) customerdesc = models.TextField() companydesc = models.TextField() userip = models.CharField(max_length=20) status = models.CharField(max_length=50) creationdate = models.DateTimeField() def __str__(self): return self.status and this is my order view @login_required(login_url='/authentication/login') def index(request): unit=Unit.objects.all() orderstatus=OrderStatus.objects.all() #order=Orders.objects.all() order =Orders.objects.select_related('customerfk') paginator = Paginator(order,20) page_number = request.GET.get('page') page_obj = Paginator.get_page(paginator,page_number) #currency = UserPreference.objects.get(user=request.user).currency context={ 'order':order, 'orderstatus':orderstatus, 'unit':unit, 'page_obj':page_obj } return render(request,'orders/index.html',context) how i can … -
<link> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a registration form to my website when I submit in web browsers (desktop) it successfully submitted but when I try to register using my browsers in mobile it shows Access to XMLHttpRequest at 'https://<link>/Member_Management/api/MembersDetails/' from origin '<link>?' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I already tried to multiple browsers from different devices this is already setup in my settings: CORS_ALLOW_ALL_ORIGINS = True # CORS configuration CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ <links> ] CORS_ALLOW_HEADERS = [ 'accept', 'authorization', 'content-type', 'x-csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] my ajax call $.ajax({ url: memberbackend_link + '/Member_Management/api/MembersDetails/', type: 'POST', data: memberData, contentType: false, processData: false, success: function(response) { How to fix the corsheaders to my website to be able to submit using mobile browsers -
Caddy for https on top of working django asgi app supposedly breacks websocket communication
I have a working django asgi application that uses channels for websocket communication with daphne and redis, and is running in a dockerized setup. To enable the secure https protocol, I tried going for a solution using caddy with selfsigned certificates (the app is deployed to a server internal to my organization). I get the caddy setup working so that I can access via https, but it seems to break the websocket part. For example, on clicking some buttons that should trigger websocket communication, I get errors like Uncaught ReferenceError: can't access lexical declaration 'ws' before initialization with a pointer to where I do a ws.send(...) in javascript. The websocket is initialized with let ws = new WebSocket('ws://' + window.location.host + '/ws/validation/'); Here is my docker-compose.yml: services: mywebapp: build: context: . dockerfile: Dockerfile.prod ssh: - default command: daphne -b 0.0.0.0 -p 8080 mywebapp.asgi:application ports: - "8080:8080" volumes: - .:/app depends_on: - redis env_file: - .env redis: image: redis:latest ports: - "6379:6379" caddy: image: caddy:latest ports: - "8081:80" - "8443:443" volumes: - ./Caddyfile:/etc/caddy/Caddyfile - /selfsigned.crt:/etc/ssl/certs/selfsigned.crt - /selfsigned.key:/etc/ssl/private/selfsigned.key depends_on: - mywebapp volumes: caddy_data: And this is my Caddyfile: example.com { tls /etc/ssl/certs/selfsigned.crt /etc/ssl/private/selfsigned.key reverse_proxy mywebapp:8080 { header_up Host {host} header_up X-Real-IP {remote} … -
difficulty to store staticfiles on S3 using STORAGES setting in django >=4.2
for file storage on AWS S3, django 4.2 introduced the STORAGES dictionary setting, replacing the individual DEFAULT_FILE_STORAGE and STATICFILES_STORAGE setting variables as explained on the django-storages documentation. I am posting this question because I do not find good resources about this "new" STORAGES dictionary setting. The documentation is light unfortunately about what the content of this STORAGES dictionary ought to be: STORAGES = { "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { ...your_options_here }, }, } adding that to... put static files on S3 via collectstatic on Django >= 4.2 you'd include the staticfiles key (at the same level as default) Referring to another source, I defined the following STORAGES dictionary in my settings.py: DEFAULT_STORAGE_BACKEND = "storages.backends.s3.S3Storage" DEFAULT_STORAGE_OPTIONS = { "access_key": os.getenv("S3_ACCESS_KEY"), "secret_key": os.getenv("S3_SECRET_KEY"), "bucket_name": os.getenv("S3_BUCKET"), "region_name": os.getenv("S3_REGION"), } STORAGES = { "default": { "BACKEND": DEFAULT_STORAGE_BACKEND, "OPTIONS": DEFAULT_STORAGE_OPTIONS, }, "staticfiles": { "BACKEND": "storages.backends.s3.S3StaticStorage" } } But when trying to collect my static files, I get the following error: 2024-11-06T04:01:52.930704485Z Collecting static files... 2024-11-06T04:01:57.469881851Z Traceback (most recent call last): 2024-11-06T04:01:57.470527987Z File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main 2024-11-06T04:01:57.474490708Z return _run_code(code, main_globals, None, 2024-11-06T04:01:57.475537977Z File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code 2024-11-06T04:01:57.475962333Z exec(code, run_globals) 2024-11-06T04:01:57.476460840Z File "/opt/project/src/manage.py", line 22, in <module> 2024-11-06T04:01:57.476786833Z main() 2024-11-06T04:01:57.476935378Z File "/opt/project/src/manage.py", … -
Python updating a global resource pool causes requests to block
Backdrop: Service basics: Django framework, cpu intensive service, start five uwsgi processes Because the underlying resource of the service is very large (2G), there are multiple versions, and this variable cannot be pickled, it is designed in the form of five processes The shape of this resource is as follows: GResource = {'key_1':resource_1, 'key_2':resource_2,'key_3':resource_3} Each request accesses this global variable GResource. At the same time, GResource is updated by BackgroundScheduler every two minutes Request time monitoring shows that when the 'GResource' cycle is updated, the request time will be higher than usual, usually 50 to 300ms, or even higher May I ask why -
uwsgi has not killed and became zombie, when stop by max-requests
I have problem... I set up configuration property 'max-requests'. When server receive requests at max-requests, uwsgi tell 'The work of process PID is done. Seeya!' and respawn worker at now But, my uwsgi became zombie process.... service 232327 0.0 0.0 0 0 ? Zl Nov05 0:06 [uwsgi] <defunct> So i configure 'vaccum', but it is not solution how do i can solve this problem.... This is my uwsgi configuration and I run server with django. [uwsgi] virtualenv = /home/service/service/.venv socket = /tmp/uwsgi_sock pidfile2=/tmp/service.pid module=project.wsgi callable=application master=true processes=1 threads=2 max-requests=2500 harakiri=15 lazy-apps=true vaccum=true logto=/var/log/service/uwsgi.log log-maxsize = 32428800 enable-threads = true ignore-write-errors=true ignore-sigpipe=true disable-write-exception=true I add configure 'vaccum'... and harakiri short.... but above harakiri seconds, process still zombieyour text -
why is my server showing bad request in the log as soon as it starts and it was working fine a few days ago
I deployed my Django project on Render, but every time I try to access the root URL (/), I receive a 400 Bad Request error. I have confirmed that my settings are configured with ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS to include the Render domain (challo-backend-1.onrender.com). My Redis server is configured to 127.0.0.1:6379 for Channels, and I’m using Django 5.1.2. ==> Your service is live 🎉 127.0.0.1 - - [05/Nov/2024:16:41:12 +0000] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" [2024-11-05 16:42:10 +0000] [95] [INFO] Handling signal: term [2024-11-05 16:42:10 +0000] [98] [INFO] Worker exiting (pid: 98) [2024-11-05 16:42:11 +0000] [95] [INFO] Shutting down: Master` """ Django settings for challo project. Generated by 'django-admin startproject' using Django 5.1.2. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ import dj_database_url from pathlib import Path from datetime import timedelta import os from django.core.exceptions import ImproperlyConfigured # Base Directory BASE_DIR = Path(__file__).resolve().parent.parent # Security settings (replace with your environment variable) def get_secret_key(): try: return os.environ['SECRET_KEY'] except KeyError: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") SECRET_KEY = get_secret_key() # Allowed Hosts and CSRF Trusted Origins ALLOWED_HOSTS = ['challo-backend-1.onrender.com', '127.0.0.1', 'localhost'] CSRF_TRUSTED_ORIGINS = ['https://challo-backend-1.onrender.com'] # Channel Layers CHANNEL_LAYERS … -
How to deploy Django app in docker with UV
I am writing a Dockerfile Configuration for a Django app. I am usin uv to manage my dependencies in a virtualenv. The app runs normally outside the container, but when I try to run it from the container, it can't find the django package: from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' This tells me that the recreation of the virtualenv inside the container is not working as it should. But I cannot find the problem. Here is my Dockerfile: FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim WORKDIR /app # Enable bytecode compilation ENV UV_COMPILE_BYTECODE=1 # Copy from the cache instead of linking since it's a mounted volume ENV UV_LINK_MODE=copy #ENV PYTHONDONTWRITEBYTECODE 1 #ENV PYTHONUNBUFFERED 1 RUN apt-get update && \ apt-get install -y --no-install-recommends gcc python3-dev libpq-dev gunicorn &&\ apt-get clean && \ rm -rf /var/lib/apt/lists/* # Install the project's dependencies using the lockfile and settings RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ uv sync --frozen --no-install-project --no-dev # Then, add the rest of the project source code and install it # Installing separately from its dependencies allows optimal layer caching ADD . /app RUN --mount=type=cache,target=/root/.cache/uv \ uv sync --frozen --no-dev #COPY --from=builder /usr/local/lib/python3.11/site-packages/ /usr/local/lib/python3.11/site-packages/ # Place executables in the environment at the … -
frontend cors error 'access-control-allow-credentials'
im using angular for my frontend and django with rest framework for my backend any request made from the front end gives the following message in my console Access to fetch at 'http://localhost:8000/login/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. this is confusing as my frontend has a interceptor which enables withCredentials export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn){ console.log(req) const modifiedRequest = req.clone({ withCredentials: true, }); return next(modifiedRequest) } and my backend has allow credentials set to true so im not sure where this error is coming from #cors settings CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] CORS_ALLOW_CREDENTIALS: True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:4200', ] CORS_ALLOW_HEADERS = ( *default_headers, ) so i removed withCredentials from my interceptor which allowed requests to go through but im using cookies for auth and none are set in my frontend when you log in -
Django + React on GPC Cloud Run, post request comes back with a 403 error
I'm attempting to submit a post request for a payment with Stripe. Despite trying many solutions on stackoverflow / reccomendations from CGPT my axios post request is still getting 403 blocked. I'm using a react frontend and a Django backend. I have a view get_csrf view looks like this. def get_csrf(request): return JsonResponse({"csrf_token": get_token(request)}) My react frontend has the following: axios.defaults.withCredentials = true; const csrf = await axios.get("https://##########################.run.app/api/get-csrf"); const csrfToken = csrf.data['csrf_token']; axios.defaults.headers.common['X-CSRFToken'] = csrfToken; Cookies.set('csrftoken', csrfToken); document.cookie shows there is a csrfcookie set. The request shows that X-CSRFToken and withCredentials are set. When submitting the from axios comes back with a 403 response. GCP logs report: Forbidden (CSRF cookie not set.): /api/create-payment-intent/ My django settings contain the following: CSRF_TRUSTED_ORIGINS = [ "https://owenmitchell.github.io", 'http://localhost:3000', "http://127.0.0.1:3000"] CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = 'owenmitchell.github.io' The reactfrontend is setup as a github pages with the above domain name. My CORS settings are: CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # Frontend URL "https://owenmitchell.github.io", "http://127.0.0.1:3000", ] CORS_ALLOW_METHODS = [ "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", ] I have django-cors-headers installed, 'corsheaders' is in my installed apps, and the cors middleware is in my middleware at the … -
Is it possible to configure leeway for authlib django?
I'm using Authlib with Django. We're migrating from one identity provider to another, and the new one has a much smaller expires_in for their tokens (going from 3600 to 60). 60 is the default leeway time, so when I try to do oauth.<idp_name>.userinfo(token=token) like I did before, it checks if the token is expired, link to definition of is_expired. I cannot pass leeway directly to authlib.integrations.django_client.OAuth() which is what I'm using to then register the IdP. It doesn't seem to be an option for the register method nor the config in settings.py. I see that leeway could be passed to OAuth2Client but I can't figure out when that class is instantiated or if I have any control over defining the variable at that point. I'm starting to think that it is simply not yet possible with the library (given that a similar demand was made previously) but I wanted to check here first before I submit a feature request. -
Why do custom managers break related object queries?
I know this is a long one, but I promise its worth a read: useful solutions, and learning about the inner workings of Django! The setup I came across this issue while working with a logged model with a ForeignKey relationship to another logged model. When deserializing an instance, I want to include its related instances. Note that I use the django_rest_framework serializers and specify the related fields in the Meta.fields option. This isn't very relevant so I won't include the code but can if requested. Tiny Example: models.py class A(models.Model): ... class B(models.Model): a = models.models.ForeignKey(A, on_delete=models.CASCADE) ... Deserializing an instance of A should return something such as: {..., 'b_set': [3, 6, 7], ...}. We get a possibly empty array of related IDs. The issue The issue arises when adding custom managers: First, we define a LoggedModelManager, all it does is filter out the logs from the current instances. Second, we define the models A and its logs ALog. A gets the custom manager -> to ensure A.objects.all() only returns instances of A, not ALog, and then we ensure ALog has the default manager (django takes care of filtering away the non-log instances). Third we do the same for … -
How to sort and show the N latest results in Django HTML template?
This is my index.html: {% extends "base.html" %} {% block content %} <table class="table table-bordered table-hover text-center"> <thead> <tr> <th>Title</th> <th>Genre</th> <th>Stock</th> <th>Daily Rate</th> <th>Date Created</th> </tr> </thead> <tbody> {% for movie in movies %} <tr> <td><a href="{% url 'movies:detail' movie.id %}">{{ movie.title }}</a></td> <td>{{ movie.genre }}</td> <td>{{movie.number_in_stock }}</td> <td>{{ movie.daily_rate }}</td> <td>{{ movie.date_created|date:'Y-m-d H:i:s' }}</td> </tr> {% endfor %} </tbody> </table> {% endblock content %} I'm learning Django and at the moment, all of the movies are shown in the index page. I'm curious how can I show the latest 10 movie order by the movie.id and in reverse? I mean the latest should be on top. I saw this question's answers but they either didn't change or show nothing. I tried these: {% for movie in movies|dictsort:"id" %} {% for movie in movies|dictsort:"movie.id" %} {% for movie in movies.sort(key=lambda movie: movie['id'], reverse=True) %} # I thought it would work in Pythonic way:( This is the last line's error: TemplateSyntaxError at /movies/ 'for' statements should use the format 'for x in y': for movie in movies.sort(key=lambda movie: movie['id'], reverse=True) Request Method: GET Request URL: http://127.0.0.1:8000/movies/ Django Version: 4.2.16 Exception Type: TemplateSyntaxError Exception Value: 'for' statements should use the format … -
Im getting this error after trying import DATABASE_URL information from the .env
File "D:\HAZEL\GITHUB\GOLDEN PROJECT\GOLDEN-DJANGO\virtual\Lib\site-packages\environ\environ.py", line 392, in get_value raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable This is my settings.py import os import dj_database_url import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env(os.path.join(BASE_DIR, '.env')) DATABASES = { 'default': dj_database_url.parse(env('DATABASE_URL')) } additionally on importing environ and dj_database_url they are underlined and show Import "dj_database_url" could not be resolved error when i hover over it... im kindly requesting for help... -
Why does my Django ORM query with naive datetimes return the same results as a PostgreSQL query with time zone-aware datetimes?
I'm using Django to filter reservations based on a date range with naive datetimes. My Django ORM query is: start_d_date_naive = "2024-11-3 00:00" end_d_date_naive = "2024-11-3 23:59" reserve_naive = Reservations.objects.filter( updated_at__range=(start_d_date_naive, end_d_date_naive), status="canceled" ) This translates to the following SQL query: SELECT * FROM "consultant_reservations" WHERE "consultant_reservations"."status" = 'canceled' AND "consultant_reservations"."updated_at" BETWEEN '2024-11-03 00:00:00' AND '2024-11-03 23:59:00' However, the results are the same as if I had run this query directly in PostgreSQL: SELECT * FROM "consultant_reservations" WHERE updated_at BETWEEN '2024-11-03 00:00:00+03:30' AND '2024-11-03 23:59:00+03:30' AND status='canceled'; Why does the Django ORM query with naive datetimes return the same results as the PostgreSQL query with time zone-aware datetimes? -
How to make an IP of a website created using Django to be a link and publicaly available to all?
I am a django learner and upon creating a website i realized that the ip of my website is not accessible on all devices but i want it to be accessed on any device using a link. I haven't tried anything about it because i don't know much about it. I am still in the learning face and am trying to get more knowledge about it. -
How to remove hidden tag on row in django if specific value was choosen in column in another row
I'm using Django to create site and need to show column only if specific value was choosen on column ie if i choose 'medium' in difficult column 'level' column show up: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Column, Row difficult = (('1', 'low'), ('2', 'medium'), ('3', 'hard'),) level = (('1', 'bad'), ('2', 'decent'), ('3', 'briliant'),) class ContactForm(forms.Form): difficult = forms.ChoiceField(choices=difficult, label='Choose level') level = forms.ChoiceField(choices=level, label='Choose level') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row(Column('difficult', css_class='form-group col-md-4 mb-0'), css_class='form-row'), Row(Column('level', css_class='form-group col-md-4 mb-0'), css_class='form-row', hidden = 'true'), Submit('submit', 'submit', css_class="btn-success") ) views.py from django.shortcuts import render from .forms import ContactForm def index(request): form=ContactForm() if request.GET: temp = request.GET['module'] print(temp) return render(request,'info.html',{'form':form}) info.html {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body style="padding:20px;"> <h1 class="mt-2" style="text-align:center;font-weight:bolder;color:steelblue;">Choose</h1> <hr class="mt-0 mb-4"> {% crispy form form.helper %} </body> </html> I know there must be js since it's tool that work on client side, but have no idea how to use that there. https://stackoverflow.com/questions/50947022/django-crispy-forms-hide-fields-conditional-on-other-field-value, but there some params and classes outside of provided code that i … -
Adding a JSON index to MYSQL may result in empty query results
After I added an index to the json field in the database, some of Django's queries stopped working, so I looked into the underlying SQL and found something strange. You can reproduce the problem with the following SQL. CREATE TABLE `products` ( `id` bigint NOT NULL AUTO_INCREMENT, `status` varchar(32) DEFAULT NULL, `info` json DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; ALTER TABLE products ADD INDEX tag_group_idx (( CAST(info->>'$."Group"' as CHAR(32)) COLLATE utf8mb4_bin )) USING BTREE; INSERT INTO products (status, info) VALUES('active', '{"Group": "G0001"}'); MySQL version: 8.0.29. OS: Windows Generated by Django SQL: SELECT * FROM products WHERE status = 'active' AND JSON_EXTRACT(info,'$."Group"') = JSON_EXTRACT('"G0001"', '$'); Result: id|status|info| --+------+----+ Using plain string SQL: SELECT * FROM products WHERE status = 'active' AND JSON_EXTRACT(info,'$."Group"') = 'G0001'; Result: id|status|info | --+------+------------------+ 1|active|{"Group": "G0001"}| Remove redundant query conditions SQL: SELECT * FROM products WHERE JSON_EXTRACT(info,'$."Group"') = JSON_EXTRACT('"G0001"', '$'); Result: id|status|info | --+------+------------------+ 1|active|{"Group": "G0001"}| As shown above, I tried three ways to query, but only the first one had empty results. I guess it was caused by the mismatch of the generated column types. I found that after I deleted the index, the first statement worked fine. ALTER TABLE products DROP … -
Admin login fails with http 403 when testing django server with locust
I'm trying to test my django server with locust, but admin login keeps on failing for 403 error. The instructions of Why am I getting a 403 error when running Locust? do not help. My logust-file: import time from locust import HttpUser, task, between class QuickstartUser(HttpUser): wait_time = between(1, 5) @task def hello_world(self): self.client.get("/tree") self.client.get("/editor/tilastot_teul/14mi/") @task(3) def view_items(self): for item_id in ["13bs","13bu", "13nw", "13nz", "14xe" ]: self.client.get(f"/editor/tilastot_teul/{item_id}") time.sleep(1) def on_start(self): r = self.client.get('') self.client.headers['Referer'] = self.client.base_url self.client.post("/admin/login/", json={"username":"admin", "password":"<my_admin_pw>", 'csrfmiddlewaretoken': r.cookies['csrftoken']}) -
Django Server ignores file changes with --reload in docker
TL;DR How to make django respond to changes I make in my code? I will post the way I run my server in docker. A base dockerfile for production Another one for dev that uses it the base The entrypoint runs the django server with --reload Observations When serving a working server, any change in any file (namely urls.py and views.py) is ignored. Adding syntax errors or any change is not reflected. When serving a server with syntax errors in urls.py for example, and when the server is still running removing the syntax error, the change does work, but any subsequent changes don't work. I checked that the files do change inside the docker container, and still Django ignores them. Here is the relevant code: Dockerfile (the base) # Use Python 3.11.3 as the base image FROM python:3.11.3-slim # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=config.settings # Set work directory WORKDIR /app # Install system dependencies and debugging tools RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ curl \ netcat-openbsd \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements.txt /app/ RUN pip install --upgrade pip && \ pip install --no-cache-dir -r requirements.txt # … -
Django caching issue when deployed to the DigitalOcean App Platform
I followed the How To Deploy a Django App on App Platform guide from DigitalOcean and successfully created a Django server which I'm using through /admin pages. Through the App Platform, I use GitHub to push changes to production. I'm having an issue with CSS and JS files that don't update after I push changes: I've tried hard refreshing my browser, using a different browser, deleting browser caches, and nothing seems to work, the files don't update. Using the Console, I can see that the files are updated on the server (including under staticfiles), but they don't update in the browser. I read up on the STORAGES setting and the ManifestStaticFilesStorage class, so I tried adding the following setting as a means of cache busting: STORAGES = { 'staticfiles': { 'BACKEND': 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage', }, 'default': { 'BACKEND': 'django.core.files.storage.FileSystemStorage', }, } When I deploy this to production, everything seems to crash except the page I'm currently on (with the JS/CSS I've been testing). I tried deploying with DEBUG=True, but this affects the execution of the static tag by changing whether Django looks for files with their regular or hashed name, so it doesn't reproduce the errors. I'm stumped, how do I even … -
When I enabled ssl using certbot, Django Channels stopped working
I want to activate ssl on my django project, but when I do it using cerbot, Django Channels doesn't work anymore. this is nginx: server { server_name mysite; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www; } location /media/ { root /var/www; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.ir/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.ir/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 = mysite.ir) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name mysite.ir; return 404; # managed by Certbot } How can I be on ssl and Django channels at the same time? -
Migrations in wrong order while setting up google sign in using oauth for my django app
I am working on a web app in django and I'm trying to setup Oauth for google sign in, my project is currently pretty much empty. I tried following a tutorial on how to set this up. Upon following the tutorial step by step I encountered multiple errors which i fixed easily (for example missing middleware setup in settings.py), but now I have encountered one I can't seem to fix. I am using PostgreSQL and when running makemigrations i always get this error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0002_token_max_lengths is applied before its dependency socialaccount.0001_initial on database 'default'. I tried faking the migrations using a tutorial provided by chatgpt and rerunning them somehow, but nothing seems to work. For the lack of a better tutorial and a lack of programming knowledge I find myself completely lost and unable to move forward. Can anyone help? -
React Query Not Returning Followings from Django API
I'm developing a React application that retrieves a user's followings from my Django backend API. However, I'm facing issues where the followings data is not being returned correctly. API Response When I make a GET request to the endpoint http://127.0.0.1:8000/api/chat/landing/, I receive a JSON response structured like this: { "current_followings": [ { "id": 1, "username": "Amir", "email": "Amir@amir.ir", "full_name": "amirali", "profile_photo": "/media/profile_photo/1000_F_244376003_1smlBNfWYSInMDUFymPuCcms6d1mOqaF_oU9kIP0.jpg", "banner_photo": "/media/banner_photo/header.jpg", "phone": null, "address": "", "bio": "", "profile_views": 1 } ], ... } The response includes an array of current_followings, each containing various fields like id, username, full_name, and profile_photo. Django views.py The view that handles this request is defined as follows: from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import Follower, BasicUserProfile # Assuming these are defined elsewhere class ChatLandingView(APIView): permission_classes = [IsAuthenticated] def get(self, request): try: current_basic_user_profile = get_current_user_profile(request, User, BasicUserProfile) current_followings = Follower.objects.filter(follower=current_basic_user_profile).select_related('following') followings_serializer = BasicUserProfileSerializer([f.following for f in current_followings], many=True) data = { "current_followings": followings_serializer.data, ... } return Response(data, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({"error": "Object not found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) This view checks for authenticated users and fetches their followings using the Follower model. It serializes the followings data before sending …