Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ubuntu server with Django, Gunicorn, Nginx does not give static
The file /var/log/nginx/error.log contains errors of the following type: [error] 714#714: *5 open() "/home/<user>/<projects>/static/css/custom.css" failed (13: Permission denied), client: ip, server: domain, request: "GET /static/css/custom.css HTTP/1.1", host: "domain", referrer: "http://domain/" The following settings are specified in the /etc/nginx/sites-available/<project> file: server { listen 80; server_name <domain>; location = /favicon.ico { access_log off; log_not_found off; } location /collected_static/ { root /home/<user>/<project>; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The following settings are specified in the /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=vsevolod Group=www-data WorkingDirectory=/home/<user>/<project> ExecStart=/home/<user>/<project>/myvenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ config.wsgi:application [Install] WantedBy=multi-user.target В файле settings.py указаны следующие настройки: STATIC_URL = '/static/' STATICFILES_DIRS = ( BASE_DIR / 'static', ) STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') Am I right in understanding that in the Nginx configuration file after location I need to specify exactly the directory that is generated after the python3 manage.py collectstatic command, so that Nginx gives it exactly that one? I ran the command sudo -u www-data stat /home/<user>/<project>/collected_static and got an error about the user not having enough rights. I ran the command sudo gpasswd -a www-data <user>, rebooted Nginx and the server just in case, but the statics still didn't … -
Django same slug but using different URL path
I am making a documentation site to self-host for myself; learning Django at the same time. I am at the point where I am starting to populate the website. I am wondering if there is a possibility to have two posts that have the same slug, but they are part of a different category. For example, I have two posts that are named "virus". One is under the category of "computer science" and the other is under the category of "heathcare". The website would link those pages as: .../healthcare/virus/ .../computer-science/virus/ Is there a way to use the same slug depending on the value of another field (e.g. category field) or some other technique? TIA -
i can develop a bulk massge software
How can I develop software that allows me to send bulk messages to customers via WhatsApp by importing a CSV file, using the official WhatsApp API, ensuring that my account remains active and does not get blocked? I need guidance on how to set up and manage this effectively. How can I develop software that allows me to send bulk messages to customers via WhatsApp -
as django fresher developer what sequence of topics need to be done? [closed]
please elaborate it I tried learning it with some tutorials of youtube, but not clear like its enough or not. I currently worked on shells, migrations, authentication and everything I need to do. I wanna land a good job as fresher in this field as python developer -
How can I change device creation to be managed only through the Client model, and restrict direct device creation?
I currently have a system where devices can be created and managed through the Device model directly. However, I want to change it so that devices can only be added or deleted through the Client model, and not directly through the Device model. Specifically, I want to: Prevent creating or modifying devices directly via the Device model. Allow adding and deleting devices only through the Client model, so when working with a Client, I can manage their devices. Ensure that when adding a device to a Client, I don’t need to re-enter the Client information, as I’m already in the context of that Client.class Client(BaseModel): inn = models.CharField(max_length=14, unique=True, verbose_name="СТИР", validators=[validate_inn]) name = models.CharField(max_length=255, verbose_name="Имя пользователя") pinfl = models.CharField(max_length=14, blank=True, null=True, verbose_name="ПИНФЛ") phone = models.CharField(max_length=13, verbose_name="Телефон", null=True, blank=True) bank_name = models.CharField(max_length=255, verbose_name="Банк") address = models.CharField(max_length=255, verbose_name="Адрес") date_birth = models.DateField(null=True, blank=True, verbose_name="Дата рождения") class Meta: verbose_name = "Клиент" verbose_name_plural = "Клиенты" def clean(self): if self.phone: self.phone = self.phone.strip().replace(" ", "") # Remove spaces if self.phone.startswith("998") and len(self.phone) == 12: self.phone = f"+{self.phone}" elif len(self.phone) == 9 and self.phone.isdigit(): self.phone = f"+998{self.phone}" def save(self, *args, **kwargs): self.date_birth = parse_birth_date(self.pinfl) super().save(*args, **kwargs) def __str__(self): return self.inn class Device(BaseModel): OWNER_CHOICES = [ ("bank", "Банк"), … -
Django + jQuery: "Add to Cart" Button Only Works for the First Product in a Loop
I am working on a Django e-commerce website where I display multiple products using a loop in my template. Each product has an "Add to Cart" button, but the issue is that only the first product’s button works. Clicking the button on any other product does nothing. Here’s my Django view function that fetches the products: def index(request): products4 = Product.objects.filter(product_status="deal_of_the_day", featured=True) return render(request, "index.html", {"products4": products4}) My Django Template (index.html): {% for p4 in products4 %} <div class="showcase-container"> <div class="showcase"> <div class="showcase-banner"> <img src="{{ p4.image.url }}" alt="{{ p4.title }}" class="showcase-img"> </div> <div class="showcase-content"> <h3 class="showcase-title">{{ p4.title }}</h3> <p class="price">${{ p4.price }}</p> <del>${{ p4.old_price }}</del> <div class="button"> <input type="hidden" value="1" id="product-quantity"> <input type="hidden" value="{{ p4.id }}" class="product-id"> <input type="hidden" value="{{ p4.image.url }}" class="product-image"> <input type="hidden" value="{{ p4.pid }}" class="product-pid"> <span id="current-product-price" style="display: none;">{{ p4.price }}</span> <span id="product-old-price" style="display: none;">{{ p4.old_price }}</span> <button class="btn add-cart-btn" type="button" id="add-to-cart-btn">Add to Cart</button> </div> </div> </div> </div> {% endfor %} My jQuery Code (main.js): console.log("Function Index"); $("#add-to-cart-btn").on("click", function(){ let this_val = $(this); if (this_val.text() === "Go to Cart") { window.location.href = '/cart/'; return; } let quantity = $("#product-quantity").val(); let product_title = $(".product-title").val(); let product_id = $(".product-id").val(); let product_price = $("#current-product-price").text().replace(/[^0-9.]/g, ''); // Strip non-numeric characters … -
Hosting a web in local server
I built web with django, and hosted it in heroku. Now I am working for a bank and going to build dashboard, but I can not host it on heroku. It should be in the local server only as far as I know. Can someone tell how the process is, in this case? Is it required to spend long time to learn how to host? Thank you! -
Form submit confirmation does not work in jQuery `ready()`
Working in Django, I am trying to update the items of a database through submitting a form. I need a confirmation dialog before submission. These are my lines on related code: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/update_in_line_orders', success: function(response){ $('#in-line-list').empty(); console.log('res'); let temp = "" for (let i in response.in_line_orders_list){ temp = temp + '<li>' + '<h2>' + 'Table No:' + response.in_line_orders_list[i]['table-no'] + '</h2>' + '<div>' for (let j in response.in_line_orders_list[i]['order']){ temp = temp + '<div>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_title'] + '</p>' + '<p class="order-item-team">' + '........' + '</p>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_quantity'] + '</p>' + '<p class="order-item-team">' + '........' + '</p>' + '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_price_rials'] + '</p>' + '</div>' } temp = temp + '</div>' + '<p class="order-item-total-team">' + 'Total' + response.in_line_orders_list[i]['total_price_rials'] + '</p>' + '<p class="date">' + response.in_line_orders_list[i]['date'] + '</p>' + '<p class="time">' + response.in_line_orders_list[i]['time'] + '</p>' + '<form id="' + String(response.in_line_orders_list[i]['order_id']) + '" method="POST">' + '{% csrf_token %}' + '<button style="font-family: Tahoma; border: none; border-radius: 20px; background-color: rgba(146,194,198,255); color: #A1662F;" name="delivered-to-table-id" value="' + response.in_line_orders_list[i]['order_id'] + '">' + 'Delivered!' + '</button>' + '</form>' + '</li>' } $("#in-line-list").append(temp) }, error: function(response){ console.log('err'); console.log(response); } }) }, 3000); }); I have tried handling the issue using … -
Gemini 2.0 experimental image generation in django
I am working on a webapp with django backend. It is related to image generation with character consistency, we finally have a model that works well for that, gemini 2.0 flash experimental. I am generating a character with openAI and then passing it as a reference to gemini via API with a prompt to generate an image. The code works perfectly in jupyter notebook, however in django, it throws an error. I am not sure how to fix it. Here is the code that works in jupyter notebook: def generate_image(request): """ Generate images using OpenAI API or Google Gemini API based on parameters """ text_prompt = request.data.get('text_prompt') use_gemini = request.data.get('use_gemini', False) character_image_url = request.data.get('character_image_url') if not text_prompt: return Response({"error": "Text prompt is required"}, status=status.HTTP_400_BAD_REQUEST) try: print(f"Generating image for prompt: {text_prompt}") print(f"Using Gemini: {use_gemini}, Character image URL: {character_image_url is not None}") # If using Gemini with a character reference if use_gemini and character_image_url: try: print(f"Generating image with Gemini: {text_prompt[:100]}...") # Download the character image response = requests.get(character_image_url) if response.status_code != 200: return Response({"error": "Failed to download character image"}, status=status.HTTP_400_BAD_REQUEST) # Load the character image into a PIL Image reference_image = Image.open(BytesIO(response.content)) # Save the reference image temporarily using standard Python tempfile … -
Django session cookies not persisting
I have a Django API which upon successful login, uses the Set-Cookie Response Headers to set a sessionId and CSRF Token in the cookies. I had it working and all of a sudden it stopped, the cookies no longer persist. After login I see them in the console, then when I refresh, they disappear. I am running my Next.js App locally with the Django API hosted on Google Cloud Run with a custom domain. Does anyone know what is going on? -
404 error on Python App deployment on CPanel
Python==3.11.11 (server ver) Django==5.1.1 Hello, today I was to deploy my app on CPanel, and everything goes fine until the end, because when configurations are all done, the page put an 404 error: Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I create the app. Make the MySQL database, do migrations just fine. Also changes some configurations on database, allow_hosts and static root in setting.py: from pathlib import Path import os, os.path # import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False #ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['https://sistema.juanjoserondon.com','sistema.juanjoserondon.com','www.sistema.juanjoserondon.com'] NPM_BIN_PATH = "C:/Program Files/nodejs/npm.cmd" INTERNAL_IPS = [ "127.0.0.1", ] TAILWIND_APP_NAME = 'theme' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_browser_reload', 'phonenumber_field', 'tailwind', 'theme', 'main', 'dashboard', 'billing', 'teaching', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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_browser_reload.middleware.BrowserReloadMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.db' ROOT_URLCONF = 'djangocrud.urls' PROJECT_PATH … -
What is the best way to have row-level authorization in django with some constraints?
I have a django app which consists of multiple different models. These models are related to each others with database relations. And somehow these relations are making a hierarchy. For example: Model City can have multiple Libraries Model Library can have multiple Books Now I can't have row-level permissions over single instances without their related instaces. its like having permission to view a certain book but not the library which it belongs to. So the case is I want to have a way to define a permission over city for example to see all of its libraries (but not book). And maybe to have a permission to see all libraries and books.. etc... What I though about is to have a rule-based authroization system to handle all the cases that might a rise by following a set of rules (it is somehow a smart and persisted way to do the authorization), but I was afraid that I am overwhelming and there might be a hidden package that I can use in django which solve this case efficiently. -
Create a Django custom Transform from an annotation
I've got an annotation for a foreign key field that I use frequently and would like to write a custom Django Transform which behaves similar to the annotation. The annotation that does what I would like is in this snippet: queryset = Event.objects.annotate(num_visits=Count("pageinfo__newpageview") + Sum(F("pageinfo__newpageview__timestamp_seconds__len"))) number_of_events_with_several_visits = queryset.filter(num_visits__gt=10).count() number_of_events_with_many_visits = queryset.filter(num_visits__gt=100).count() event_with_most_visits = queryset.order_by('-num_visits').first() I'd like to turn this annotation into a custom Transform so I can use it in multiple situations without having to repeat the annotation. The framework of the Transform would be: class NumVisitsTransform(models.lookups.Transform): lookup_name = "num_visits" # Some implementation goes here page_info_field = Events._meta.get_field("pageinfo").field page_info_field.register_lookup(NumVisitsTransform) My goal with this Transform is to enable then re-writing the examples above, without respecifying the annotation to be: number_of_events_with_several_visits = queryset.filter(pageinfo__num_visits__gt=10).count() number_of_events_with_many_visits = queryset.filter(pageinfo__num_visits__gt=100).count() event_with_most_visits = queryset.order_by('-pageinfo__num_visits').first() Is there a straight-forward way to write the implementation of the Transform using the annotation and above building it up from the expressions in the annotation? Even a simpler example building a Transform using sub-expressions would be useful. I tried to implement a template for the SQL in the Transform but this was quickly getting beyond my capability in SQL. I was hoping there might be a way to build this up without … -
Why does duplicating a Django filter condition change PostgreSQL’s query plan estimates?
I'm working on a Django project with PostgreSQL and have implemented a custom filter to select "active" records. The filter is defined as follows: def get_custom_filter(qs): return qs.filter( Q( Q(timestamp_field__lte=timezone.now(), related_obj__delay__isnull=True) | Q( related_obj__delay__lte=timezone.now(), type_obj__flag=False, timestamp_field__isnull=False, ) | Q(type_obj__flag=True, timestamp_field__lte=timezone.now()) ) ) I then create a custom filter backend: class CustomFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, qs, view): return get_custom_filter(qs) In my view, I include this filter in the filter_backends list. Here’s what happens: When I include CustomFilterBackend only once, the PostgreSQL query plan shows that after filtering the estimated number of rows for sorting/uniquing is around 7,200 rows. For example, the WHERE clause appears as: WHERE ("tenant_table"."tenant_id" IN (1) AND (("main_table"."delay_field" IS NULL AND "primary_table"."timestamp_field" <= TIMESTAMP) OR (NOT "type_table"."flag" AND "main_table"."delay_field" <= TIMESTAMP AND "primary_table"."timestamp_field" IS NOT NULL) OR ("type_table"."flag" AND "primary_table"."timestamp_field" <= TIMESTAMP)) AND NOT ( ... )) When I duplicate the filter (include it twice), the plan shows an estimated row count of about 2,400—roughly one third of the original estimate. The WHERE clause now contains two copies of the active filter condition: WHERE ("tenant_table"."tenant_id" IN (1) AND (("main_table"."delay_field" IS NULL AND "primary_table"."timestamp_field" <= TIMESTAMP) OR (NOT "type_table"."flag" AND "main_table"."delay_field" <= TIMESTAMP AND "primary_table"."timestamp_field" IS NOT NULL) OR … -
Why does my uwsgi app respond with prematurely closed connection?
I can serve my django app running uwsgi --socket lhhs/lhhs.sock --module lhhs/lhhs.wsgi --chmod-socket=664 And the django app runs quick and running python manage.py test shows it is fine. But uisng nginx and uwsgi-emperor I get upstream prematurely closed connection while reading response header from upstream, client: 74.45.12.120, server: lhhs.oh-joy.org, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///var/www/webapps/lhhs/lhhs/lhhs.sock:", host: "lhhs.oh-joy.org" Here is my .ini file: uid = www-data chdir=/var/www/webapps/lhhs/lhhs home=/var/www/webapps/lhhs/env home=/var/www/webapps/lhhs/env module=lhhs.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/var/www/webapps/lhhs/log/lhhs-uwsgi.log socket=/var/www/webapps/lhhs/lhhs/lhhs.sock chmod-socket = 664 Here is my nginx config: upstream django { server unix:///var/www/webapps/lhhs/lhhs/lhhs.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } server { listen 443 ssl; server_name lhhs.oh-joy.org; charset utf-8; ssl_certificate /etc/letsencrypt/live/lhhs.oh-joy.org/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/lhhs.oh-joy.org/privkey.pem; # managed by Certbot location /static { alias /var/www/webapps/lhhs/lhhs/static; } location /media { alias /var/www/webapps/lhhs/lhhs/media; } location /favicon.ico { alias /var/www/webapps/lhhs/lhhs/static/images/favicon.ico; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; } } server { if ($host = lhhs.oh-joy.org) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name lhhs.oh-joy.org; return 404; # managed by Certbot } -
Django/CKEditor - config for extraProviders
How can I configure a simple extraProvider for local media in my CKEDITOR_5_CONFIGS in the settings.py file? I tested the configuration below via javascript and it worked fine, but when I switched to python, I got the error Uncaught CKEditorError: this._previewRenderer is not a function. I'm almost giving up and moving on to another alternative, such as directly editing the app.js file of the django-ckedtor-5 library. Any suggestions? CKEDITOR_5_CONFIGS = { ... 'mediaEmbed': { 'previewsInData': True, 'extraProviders': [ { 'name': 'LocalProvider', 'url': '/^https?:\/\/[^\/]+\/media\/videos\/(.+\.(mp4|avi|mov|webm|ogg|mkv))$/', 'html': 'match => `<video width="640" height="360" controls><source src="${match[0]}" type="video/${match[2]}">Seu navegador não suporta vídeo.</video>`' }, ] } } -
I can't solve the migration problem in django
I put the oracle db that I was currently developing with django and oracle into the db that impdp and distributed it. However, the distribution db has a different schema name from the development db, so it is not possible to properly migrate. Also, because I impdp, tables such as django migrations have also been handed over to the distribution db. How can I do the migration properly here? Also I want to impdp varoown/varoown99@varo directory=dump dumpfile=varolig_dump4.dmp remap_schema=varo:varoown transform=segment_attributes:n logfile=import.log I did an impdp with the following command And when I checked with python manage.py dbshell, I also checked that db is properly connected -
Deploy logs "--error-logfile/--log-file" railway with django
I'm deploying my django app for the very first time on railway. On railways in the project deployment details I see: enter image description here However when I go in the deploy logs I see this error "gunicorn: error: argument --error-logfile/--log-file: expected one argument usage: gunicorn [OPTIONS] [APP_MODULE]" : enter image description here It seems that the issue comes from the Procfile: My ProcFile contains: web: gunicorn telecom_tracker.telco_tracker.wsgi I tried several alternative but still get the same issue. My project follows the following structure: enter image description here Any idea what could be the bug root ? thanks in advance !! -
Error when applying migrations 'no password supplied', but I can connect to the database from the interpreter
I decided to revive my pet project that I wrote 2 years ago. First I had to update all dependencies, this is ok. But migrations are not performed when working with a local server. The pg_hba.conf file has md5. At the same time, if I connect to the DB from the interpreter via psycopg2, everything works fine. This is what traceback shows enter image description here enter image description here I would like to quickly figure this out, so I am writing here, maybe someone has encountered this and can help right away. If not, I will, of course, dig into the modules from the traceback. Thanks in advance for your answer! -
Is there a way to define an authentication for webhooks in DRF Specacular
I have the following webhook definition change_event_webhook = OpenApiWebhook( name="AddonWebhook", decorator=extend_schema( summary="A Webhook event", description="Pushes events to a notification URL. ", tags=["webhooks"], request={"application/json": load_schema("myschema.json")}, responses={ "2XX": OpenApiResponse("Event was received successfully"), }, ), ) which produces the following schema ... webhooks: AddonWebhook: post: description: 'Pushes events to a notification URL. ' summary: A Webhook event for an addon tags: - webhooks requestBody: content: application/json: schema: $id: https://my-schema.url/schema.json $schema: http://json-schema.org/draft-07/schema# title: Webhooks messaging additionalProperties: false definitions: {} type: object required: - change_id - action properties: change_id: title: Change ID type: integer description: Numerical ID of change action: title: Change Action type: string description: Verbose name of the change responses: 2XX: content: application/json: schema: type: object additionalProperties: {} description: Unspecified response body description: '' My redocly rules sets the security as required, so when linting my schema, I get the following error "Every operation should have security defined on it or on the root level." How can I add an authentication method (lik HMAC) to my webhook definition ? The desired result would then include something like security: - signatureAuth: [] -
How to Automatically Copy Product Attributes to Variants in Django Models?
I am building an e-commerce website in Django where: A Product can have multiple variants. Each product has attributes (e.g., color, storage, display size). I want each variant to automatically inherit all attributes from the main product when it is created. Models (models.py) from django.db import models class Product(models.Model): name = models.CharField(max_length=255) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") name = models.CharField(max_length=255) # Example: "Iphone 16 Black 128GB" class ProductAttribute(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="attributes") attribute_name = models.CharField(max_length=255) attribute_value = models.TextField() What I Want to Achieve: When a ProductVariant is created, it should automatically copy all attributes from its main product. What is the best way to do this in Django? I want a clean and efficient solution that works well even if I have many variants. Any guidance would be appreciated. Thank you! -
Programmin Error at Routes , i am not getting why is the happening , please help me?
ProgrammingError at /routes/ column airline_app_route.route_id does not exist LINE 1: SELECT "airline_app_route"."route_id", "airline_app_route"."... ^ Request Method: GET Request URL: http://127.0.0.1:8000/routes/ Django Version: 5.1.7 Exception Type: ProgrammingError Exception Value: column airline_app_route.route_id does not exist LINE 1: SELECT "airline_app_route"."route_id", "airline_app_route"."... ^ Exception Location: D:\DEVELOPMENT\VIR_ENV\Lib\site-packages\django\db\backends\utils.py, line 105, in _execute Raised during: airline_app.views.route_list Python Executable: D:\DEVELOPMENT\VIR_ENV\Scripts\python.exe Python Version: 3.13.1 Python Path: ['D:\DEVELOPMENT\airline_reservation', 'D:\Python\python313.zip', 'D:\Python\DLLs', 'D:\Python\Lib', 'D:\Python', 'D:\DEVELOPMENT\VIR_ENV', 'D:\DEVELOPMENT\VIR_ENV\Lib\site-packages'] Server time: Wed, 19 Mar 2025 07:02:57 +0000 -
How to cache python pip requirements of docker build progress?
I'm on a very slow internet connection, and the RUN pip install -r requirements.txt step of docker compose up --build keeps timing out halfway through. When I run docker compose up --build again, it looks like it restarts from the very beginning. All of the python packages get downloaded from scratch. How can I make docker use the downloaded packages from the previous attempt? -
Django + Next cookies not being set when app is hosted
I have a Django app hosted on Google Cloud Run that upon logging in, sets a sessionid and csrftoken in the browser cookies. In my frontend Next app, which I am currently running locally, I redirect to an authenticated page after successful login. However, the cookies are not being set correctly after the redirect, they are empty. After making the login call I can see the cookies in the Application DevTools console, but when I refresh or redirect they are empty. It works when running my Django app locally, but not when it is hosted on Cloud Run. These are my cookie settings in my Django settings.py: SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = False CORS_ALLOW_CREDENTIALS = True My CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS includes my local Next app: http://localhost:3000. I had this working and I am not sure what changed and it is suddenly not. Any help with this would be greatly appreciated! -
Django Docker container unable to connect to Supabase PostgreSQL: Network is unreachable
I'm working on a Django project with Docker, and I'm trying to connect to a Supabase PostgreSQL database. On my local machine, I can connect to the database using the psql command, but when I try to connect from inside the Docker container, I get the following error: connection to server at "db.*********.supabase.co" (2a05:d012:42e:5700:63e9:906e:3eeb:5874), port 5432 failed: Network is unreachable Is the server running on that host and accepting TCP/IP connections? Request Method: POST Request URL: http://13.60.86.154:8000/api/user/register/ Django Version: 4.2.20 Exception Type: OperationalError Exception Value: connection to server at "db.*********.supabase.co" (2a05:d012:42e:5700:63e9:906e:3eeb:5874), port 5432 failed: Network is unreachable Is the server running on that host and accepting TCP/IP connections?``` What I’ve tried: I can connect to the database from my local machine using psql, but not from within the Docker container. The Docker container is running and listening on ports 8000 (backend) and 3000 (frontend) with docker-compose. The error indicates that the connection is being refused because of a "network unreachable" issue. I’ve checked if Docker containers are using IPv6 (the IP shown is an IPv6 address), but the issue persists. What could be causing this issue? How can I resolve it?