Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PWA offline template not showing
why my django pwa offline template is not showing i checked everthing is in its position and also there is to typo mistakes my offline.html is in write path templates/patients/offline.html and i also added PWA_APP_OFFLINE_TEMPLATE = 'patients/offline.html' in my settings.py and also in my project urls.py `urlpatterns = [ path('admin/', admin.site.urls), path('',include('patients.urls')), path('', include('pwa.urls')), ]` my pwa is working fine but online my offline template is not showing i checked in devtools in chrome and in application my service worker and manifest.json is good and activated and in also cache storage i see that /offline/ anyone can help to solve this issue -
How can I move an iterable value from an outer loop to an inner loop without iterating through the inner loops?
How can I move the iterable value (radio) from the outer loop to the inner one, bypassing the inner loop iteration? How can I get the value (radio) of the outer loop. I have a nested loop that generates additional fields. The value from the outer loop. I plan to get the value from the outer loop not 30 times - but how many times in the outer loop 5 times. How can I skip the inner iteration? <fieldset> <legend>{{ form_2.name_working.label }}</legend> {% for radio in form_2.name_working %} {% for i in kol_vo_iteracii_categ|get_range %} <a>Cat</a> <div class="myradio"> {{ radio }} </div> {% endfor %} {% endfor %} </fieldset> -
How to use Django Q objects with ~Q() inside annotate(filter=...) to exclude a value?
I'm refactoring a legacy Django Job to use annotate with filtered Count aggregations instead of querying each record individually (avoiding the N+1 problem). I want to count the number of related EventReport objects per Store, excluding those where status="C". So I wrote something like: stores_with_monitoring_enabled.annotate( total_cards=Count( 'eventreport', filter=Q( eventreport__event_at__gte=day_30_days_ago_start, eventreport__event_at__lte=yesterday_end ) & ~Q(eventreport__status='C') ), # ... etc But Django raised SyntaxError: positional argument follows keyword argument. I also tried: # ... etc filter=Q( eventreport__event_at__gte=start_date, eventreport__event_at__lte=end_date ) & ~Q(eventreport__status="C") # ... etc But I'm unsure if this is the correct pattern inside annotate()'s filter. I expected to get only related objects where `status != "C" without any errors. PS: I looked into other solutions on StackOverflow and the suggestions on this one: How do I do a not equal in Django queryset filtering?, but I could'nt get it working when using Q() alongside ~Q() with other kwargs. What’s the best approach to express status != 'C' inside a Count(..., filter=...) clause? -
How to use CustomUser with dj_rest_auth to sign up with email and password
How to use CustomUser with dj_rest_auth to register with email and password. I have the source code below, but the username information is required during the sign-up process. I would like to know how to sign up with only the email, password1, and password2 information. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'dj_rest_auth', 'dj_rest_auth.registration', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware' ] SITE_ID = 1 AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_FIELDS = ['email', 'password1', 'password2'] ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'none' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer', } accounts/models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email accounts/serializers .py from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): return { 'email': self.validated_data.get('email', … -
Slug is not created correctly due to using django parler
I have a problem creating a slug based on the title and pk, due to the use of parler. I'm using Parler for multilinguality in my API, and when I try to create a slug like title-pk I'm getting various bugs. My model: class Events(TranslatableModel): ... translations = TranslatedFields( title=models.CharField(max_length=255, verbose_name=_("Event title")), body=MDTextField(verbose_name=_("Event body")), ) slug = models.SlugField(blank=True, max_length=255, verbose_name=_("Event slug")) ... So, I tried using the save() method, but I got a slug like -None or -pk. def save(self, *args, **kwargs): if not self.slug: title = self.safe_translation_getter("title", language_code="uk") base_slug = slugify(title) self.slug = f"{base_slug}-{self.pk}" super().save(*args, **kwargs) I also used a signal, which also did not work. @receiver(post_save, sender=Events) def generate_slug_after_translation(sender, instance, **kwargs): if not instance.slug: uk_title = instance.safe_translation_getter("title", language_code="uk") if uk_title: base_slug = f"{uk_title}-{instance.pk}" instance.slug = slugify(base_slug)[:255] instance.save(update_fields=["slug"]) What did I do wrong, and what should I do next? -
Take a long time I load the Django library using PyCharm
Why does it take a long time I load the Django library using PyCharm? steps: I had created a New Project import django, but prompt error Install django Package in Interpreter it doesnt take long time I install other package. Is there something wrong with settings? -
How can I pass the values of list elements by index to the template - as the number of iterations of the loop?
How can I pass the values of list elements by index to the template - as the number of iterations of the loop? I have a loop in the template and I would like to pass the number of iterations in the loop - as the value of the element in the list. [10, 5, 8] - each element of the list is the required number of iterations. list_2 = [10, 5, 8] j = 0 i = 0 {% for len(list_1) ...number of iterations... in %} <a>list_1[j]</a> {% for list_2[j] ...number of iterations... in %} <div> {{ list_3[i] }} i = i + 1 </div> {% endfor %} j = j + 1 {% endfor %} <div> <fieldset> <legend>{{ form_2.name_working.label }}</legend> {% for radio in form_2.name_working %} <div class="myradio"> {{ radio }} </div> {% endfor %} </fieldset> </div> -
python manage.py migrate failed
Created a database in aws.amazon.com, edited the setting.py file in my django project, tried to migrate in the virtual environment and got error message which include as stated below: port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? Where did I get it wrong? typed "python manage.py migrate" and expected the setting.py changes made to connect my django project to database created on aws.amazon.com -
The drop-down list when hovering over the element field when the contents of the line is long? (Django-Select2)
Good day! I have data to display in a row. I use such an element as a choice in a drop-down list. I have a very large long line of about 100 characters and I would like to have line breaks. I plan to display a drop-down list in a form. I read that you can come up with something like this - shorten the line - the number of words, characters and make the end of the list in the form of three dots. And when hovering or selecting an element, open something like tooltips with the full name of the content when hovering. Is it possible to do something similar through such add-ons as? Django-Select2 django-autocomplete-light -
django deploy on pythonanywhere, unhandled-exception error
I'm looking for help since I'm stuck with the deploy (for testing) of my django website. First deploy ever, so expect inaccuracies. I cannot view my site: when I click on the link I get a 'Something went wrong. There may be a bug in your code.Error code: Unhandled Exception". It is likely in wsgi code, since this is the error log and I get the same result putting IIPH.settings or Iiph.settings in wsgi file: 2025-07-06 21:14:54,888: ModuleNotFoundError: No module named 'IIPH' 2025-07-06 21:14:54,888: File "/var/www/mynickname_pythonanywhere_com_wsgi.py", line 26, in 2025-07-06 21:14:54,888: application = get_wsgi_application() 2025-07-06 21:14:54,888: 2025-07-06 21:14:54,888: File "/home/mynickname/.virtualenvs/env/lib/python3.13/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2025-07-06 21:14:54,889: django.setup(set_prefix=False) 2025-07-06 21:14:54,889: ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^ 2025-07-06 21:14:54,889: 2025-07-06 21:14:54,889: File "/home/mynickname/.virtualenvs/env/lib/python3.13/site-packages/django/init.py", line 19, in setup 2025-07-06 21:14:54,889: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2025-07-06 21:14:54,891: File "/home/mynickname/.virtualenvs/env/lib/python3.13/site-packages/django/conf/init.py", line 68, in _setup 2025-07-06 21:14:54,891: self._wrapped = Settings(settings_module) 2025-07-06 21:14:54,892: If you're seeing an import error and don't know why, 2025-07-06 21:14:54,892: we have a dedicated help page to help you debug: 2025-07-06 21:14:55,435: Error running WSGI application 2025-07-06 21:14:55,437: ModuleNotFoundError: No module named 'IIPH' 2025-07-06 21:14:55,437: File "/var/www/mynickname_pythonanywhere_com_wsgi.py", line 26, in 2025-07-06 21:14:55,438: application = get_wsgi_application() 2025-07-06 21:14:55,438: 2025-07-06 21:14:55,438: File "/home/mynickname/.virtualenvs/env/lib/python3.13/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2025-07-06 21:14:55,438: django.setup(set_prefix=False) 2025-07-06 … -
Using Openlayers GeoTIFF sources in a django app
I have a django app with a page that displays OSM through Openlayers, I dynamically add some markers to it and now I also want to display raster overlays from .tif files. I am struggeling to implement Openlayers GeoTIFF. This is my current testing template, where i am just trying to get any tif file to display. I am using a local copy of the openlayers code here: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <link rel="stylesheet" href="{% static '/css/ol.css' %}"> <script src="{% static '/js/ol.js' %}"></script> <script type="module" src="{% static '/ol/source/GeoTIFF.js' %}"></script> <script src="{% static '/js/proj4.js' %}"></script> </head> <body id="body"> <div id="map" style="width: 1000px; height: 500px;"></div> </body> <script type="module"> const source = new GeoTIFF({ sources: [ { url: 'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/36/Q/WD/2020/7/S2A_36QWD_20200701_0_L2A/TCI.tif', }, ], }); const layer = new TileLayer({ source }); const map = new Map({ target: 'map', layers: [layer], view: new View({ center: [0, 0], zoom: 12, }), }); </script> </html> This doesnt work because GeoTIFF.js is trying to import from 'geotiff', which it cant find. I know I probably have to go through the npm install and somehow bundle the dependencies to use GeoTIFF in a template like this but I … -
Celery Pytest integration test not working properly with django emails
I made a task for celery and tested it with as a unit with this test: @pytest.mark.django_db def test_document_expiry_alert_unit(settings): settings.CELERY_TASK_ALWAYS_EAGER = True manager = UserFactory( email="manager@mail.com", role=Role.MANAGER, organization__check_docs=True ) doc = EmployeeDocumentFactory(user__organization=manager.organization) mail.outbox = [] document_expiry_alert.delay() assert len(mail.outbox) == 1 sent = mail.outbox[0] html_content = sent.alternatives[0][0] assert manager.email in sent.to assert doc.get_type_display() in html_content assert doc.user.get_full_name() in html_content assert "documents are expiring tomorrow" in sent.body It worked and the test passes, then I tried to make an integration test, so I installed celery[pytest] and add the config in pytest along with the plugin in conftest.py, celery.contrib.pytest Now I tried running this test: @pytest.mark.django_db(transaction=True) def test_document_expiry_alert_intergration(celery_app, celery_worker): manager = UserFactory( email="manager@mail.com", role=Role.MANAGER, organization__check_docs=True ) EmployeeDocumentFactory(user__organization=manager.organization) mail.outbox = [] celery_app.send_task("organizations.tasks.document_expiry_alert") celery_worker.reload() assert len(mail.outbox) == 1 assert manager.email in mail.outbox[0].to But I get this error FAILED tests/organizations/task_tests.py::test_document_expiry_alert_intergration - assert 0 == 1 which means the mailbox has no mail sent, I tried using @patch to mock the send, but I got also zero call counts. The logs and print statements are showing in my terminal when running the test, so everything before the point I send the email, everything works. I'm using django.core.mail.EmailMultiAlternatives to send the email. -
How to get count and show in template - Django
I was able to get the mutual friends from each users and display each mutual friends image on my template as seen in the attached image to this question. The problem now is that I was not able to get the count, like count and length is not working on template. How can I get it done? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True) following = models.ManyToManyField( 'Profile', # Refers to the User model itself symmetrical=False, # If A follows B, B doesn't automatically follow A related_name='followers', # Reverse relationship: get followers of a user blank=True, ) def FollowingView(request): page_title = "Following" # All account users profile_users = Profile.objects.exclude( Q(user=request.user)) # Mutual Followers all_following = request.user.profile.following.values_list('pk', flat=True) mutual_followers = Profile.objects.filter(pk__in=all_following) Template: {% for users in profile_users %} # List of users <p>{% users.user %}</p> {% for user_following in mutual_followers %} {% if user_following in users.following.all %} <img src="{{ user_following.user.profile.profile_pic.url }}" class="hover-followers-img"/> {{ user_following.count }} # Not getting count {% endif %} {% endfor %} {% endfor %} -
ECS Fargate Service task running but Target Group shows unhealthy and curl to localhost:8000/health fails
Problem Summary: I’ve deployed a Django backend in ECS using EC2 launch type (not Fargate), behind an Application Load Balancer (ALB). The service runs a containerized Gunicorn server on port 8000, and the health check endpoint is /health/. While ECS shows one task running and healthy, the Target Group shows the task as unhealthy and curl to localhost:8000 fails from the EC2 instance. Setup Details ✅ Django App URL path for health check: def health_check(request): return JsonResponse({"status": "ok"}, status=200) path("health/", views.health_check, name="health_check"), Dockerfile: FROM python:3.12 ENV PYTHONUNBUFFERED=1 WORKDIR /app # Install pipenv RUN pip install --upgrade pip RUN pip install pipenv # Install application dependencies COPY Pipfile Pipfile.lock /app/ # We use the --system flag so packages are installed into the system python # and not into a virtualenv. Docker containers don't need virtual environments. RUN pipenv install --system --dev # Copy the application files into the image COPY . /app/ # Expose port 8000 on the container EXPOSE 8000 CMD ["gunicorn", "Shop_Sphere.wsgi:application", "--bind", "0.0.0.0:8000"] ECS task definition: { "taskDefinitionArn": "arn:aws:ecs:ap-south-1:562404438272:task-definition/Shop-Sphere-Task-Definition:7", "containerDefinitions": [ { "name": "Shop-Sphere-Container", "image": "adsaa/ee:latest", "cpu": 0, "portMappings": [ { "name": "django-port", "containerPort": 8000, "hostPort": 8000, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [ { … -
accounts/login/ is not mapped when only root paths to its hosted app is not specified
I am using django 5.2.3 and I am trying to use the built-in login system, for that I have defined the path inside my app users/urls.py: from django.urls import path, include from . import views urlpatterns = [ path("accounts/", include("django.contrib.auth.urls")), ] Now the thing is that if I go to the url http://127.0.0.1:8000/accounts/login/ it will throw the following error: The current path, accounts/login/, didn’t match any of these. I fixed the issue by adding the following path to the url dispatcher inside urls.py at the project level (my project/urls.py): urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls')) # This fixed the issue ] And now the login form displays correctly at http://127.0.0.1:8000/accounts/login/ HOWEVER, when I tried with a different path, like the following, it doesn't work: urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')) # This doesn't work, same error thrown ] My question is, why it does work with path('', include('users.urls')) and not path('users/', include('users.urls')) ? Thanks in advance -
On submitting the code, the submission is on pending
Here is my github - https://github.com/HemantRaj-2005/online-judge I am making backend in django and frontend in vite react with typescript It is a online judge, but on submitting code, it only shows pending.., getting nothing neither on console nor on terminal, so unable to figure out the mistake The files related to judge part is in backend |-judge/ frontend |-src |-pages |-Problem |-service please ignore the docker-compose.yml file, I tried threading so shifted on cerelary with redis, and also using local executor still facing the same issue -
I want to implement a reports and analytics code in django
This is the reports app for a business management website. One of its features is to identify the top selling product on the platform.Another is that it process low stock alerts,identify stock which has no sales. Also, it should display a table for the product, the units sold, total price of the products and if the product is available.Finally, the report app needs to count order based a date range. It should add revenue generated and filter revenue.enter image description here -
Could not connect to Saleor during installation. Saleor URL that App tried to connect: http://localhost:8000/graphql/
I'm using self hosted Saleor and trying to integrate self hosted stripe app, however I'm getting "Couldn’t Install Stripe The auth data given during registration request could not be used to fetch app ID. This usually means that App could not connect to Saleor during installation. Saleor URL that App tried to connect: http://localhost:8000/graphql/" I'm not sure why saleor url is http://localhost:8000/graphql/ since all variables in my env point to my deployed server api url and not localhost. Nothing is running locally, i'm using my deployed dashboard to install a deployed stripe app. -
How to get mutual friends - Django
I have been able to get the list of all users and also implement sent friend request (following/follower). Now, how do I get mutual friends(following/followers)? For example; if both user have an existing friend in common. Below code is what I have tried, but not displaying mutual friends. What am I doing wrong and how can I get it done correctly? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True) following = models.ManyToManyField( 'Profile', # Refers to the User model itself symmetrical=False, # If A follows B, B doesn't automatically follow A related_name='followers', # Reverse relationship: get followers of a user blank=True, ) def FollowingView(request): page_title = "Following" # All users following posts posts = Post.objects.filter( Q(poster_profile=request.user)| Q(poster_profile__profile__followers__user=request.user)).order_by("?").distinct() # All account users profile_users = Profile.objects.exclude( Q(user=request.user)) # Mutual Followers all_following = request.user.profile.following.values_list('pk', flat=True) mutual_followers = Profile.objects.filter(pk__in=all_following) -
I am building a system mixed of tiktok and amazon store where we can post the video as well and buy products [closed]
Suggest me the technologies and the architecture that I can follow for 1 millions users -
после попытки контеризировать приложения события Celery перестали обрабатываться
я написал простой сайт на Django по покупке билетов, Celery когда пользователь начинает процесс оплаты места, оно бронируется. если через n секунд он все еще не оплатил - то оно освобождается с помощью Celery. когда я запускал сайт локально (поднимая worker and redis manually), то всё работало корректно. Перед контеризацией я изменил настройки для celery: CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' поменял localhost на redis, потому что слышал что Docker делает сетевым именем контейнера то, что указано в docker-compose dockerfule: FROM python:3.11-slim WORKDIR /app COPY . . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD ["python3", "Tickets/manage.py", "runserver", "0.0.0.0:8000"] docker-compose: services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" container_name: ticket-web worker: image: ticket-web working_dir: /app/Tickets command: celery -A Tickets worker depends_on: - redis - web redis: image: redis:6-alpine ports: - "6379:6379" celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Tickets.settings') app = Celery('Tickets') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.update( timezone='Europe/Moscow', # Set your preferred timezone enable_utc=False, ) app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') init: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) логи worker: SecurityWarning: You're running the worker with superuser privileges: this is … -
Unable to run tests django. django.db.utils.ProgrammingError: relation "auth_user" does not exist
I'm writing tests. When trying to run it, it returns the error "django.db.utils.ProgrammingError: relation "auth_user" does not exist". I'm running the project locally using a virtual environment. There is a similar error in the logs in pgadmin. This error also occurs when starting a project in docker. I checked the migrations. I tried all the options from the Internet and GPT. I will be very grateful for your help. -
gunicorn gevent CERTIFICATE_VERIFY_FAILED error
I have a Django website running in a Docker container (Debian), which I deploy with the following command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 33 --worker-class gevent --timeout 1200 I created a simple view with an outgoing request: def my_view(request): import requests requests.get('https://website.domain.com', verify='/etc/ssl/certs/mycert.cer') return HttpResponse('Success') Which throws the error: requests.exceptions.SSLError: HTTPSConnectionPool(host='website.domain.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)'))) What could be the reason for such behavior? What is special about how the gevent worker handles SSL certificates? What I found out for now: The script works fine when I use --worker-class sync or deploy with python manage.py runserver The script works fine when executed via python console or via python manage.py shell (from a running docker container) The certificate is correct (otherwise, it didn't work for cases above) Unsetting REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, SSL_CERT_FILE or setting them to current location of my cert file doesn't help PYTHONHTTPSVERIFY=0 seems to have no effect verify=False and verify=True have no effect Adding monkey.patch_all() in the script has no effect Adding gunicorn.conf.py with monkey.patch_all() in it has no effect The certificate is definitely being used. Because if I set verify parameter … -
Wagtail login downgrades to http, gives error
I am setting up a new, local version of a Django Wagtail project (which I have had running locally before). I am able to see Pages in my browser, but when I try to login (on FF, Chrome, Safari-with-no-plugins) at https://mysite.test/admin/login/?next=/admin/ I get the error: gaierror at /admin/login/ [Errno -2] Name or service not known Request Method: POST Request URL: http://mysite.test/admin/login/ Django Version: 5.0.3 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python3.10/socket.py, line 955, in getaddrinfo Raised during: wagtail.admin.views.account.LoginView Python Executable: /root/uv/.venv/bin/python Python Version: 3.10.12 Python Path: ['/usr/srv/app', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/root/uv/.venv/lib/python3.10/site-packages', '/root/uv/.venv/lib/python3.10/site-packages/setuptools/_vendor'] Server time: Thu, 03 Jul 2025 13:44:22 +0000 which includes the request URL http://mysite.test/admin/login/. I don't have a VPN running and I can't identify anything else which might be causing trouble on the local network (though I can't discount this). If I try https://127.0.0.1:5000/admin I get: Secure Connection Failed An error occurred during a connection to 127.0.0.1:5000. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the web site owners to inform them … -
Django media images not loading in production using Nginx , with Debug=False
I'm deploying my Django project with DEBUG=False, and media files like images are not loading. Nginx Configuration server { listen 80; listen [::]:80; server_name <my_server_ip>; location /media/ { alias /home/ubuntu_server02/cdo_portal/media/; autoindex on; } location / { proxy_pass http://127.0.0.1:8000; 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; } } Django settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') What are the details of your problem? I deployed my Django project with DEBUG=False, and I'm trying to serve uploaded media files (images) using Nginx. However, when I access a media file through the browser (e.g., http://<server_ip>/media/sample.jpg), I get a 404 Not Found error. The media files exist in the correct folder, Nginx is running, and permissions are correct. I'm not sure if the issue is with my Nginx config or something else. What did you try and what were you expecting? I tried accessing media files through the browser directly, like: http://<my_server_ip>/media/sample.jpg I expected the image to load, but it returned a 404. I checked that the file exists, the path in Nginx is correct, and the alias points to the right folder. Still, Nginx doesn't seem to serve the media files.