Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django-mptt using get_root() on TreeQuerySet element inside for loop and output stored in list does not persist outside of for loop
I am trying to use get_root() on individual TreeQuerySet elements in a for loop. This seems to work in the Django Python shell as shown below. Upon pressing [Enter] twice to indicate the end of the for loop, the result of applying the get_root() to each element is printed automatically in the shell. The result is correct in that the output does indeed list the top level root of each TreeQuerySet element. However outside of the loop, the list in which these should be stored in is not updated. Instead this list contains the original TreeQuerySet elements. In Django Python shell: >>> topics_w_arttype_articles = topics.Topic.objects.filter(to_ArtTypeArticle_topic_from_Topic__title__isnull=False).distinct() >>> topics_w_arttype_articles <TreeQuerySet [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>]> >>> arttype_topic_roots_list = [] >>> for item in topics_w_arttype_articles.iterator(): ... item.get_root() ... arttype_topic_roots_list.append(item) ... <Topic: Level0Topic1> <Topic: Level0Topic2> <Topic: Level0Topic2> <Topic: Level0Topic3> <Topic: Level0Topic4> <Topic: Level0Topic5> <Topic: Level0Topic5> <Topic: Level0Topic5> >>> arttype_topic_roots_list [<Topic: Level1Topic1>, <Topic: Level1Topic2>, <Topic: Level1Topic3>, <Topic: Level1Topic4>, <Topic: Level2Topic1>, <Topic: Level2Topic2>, <Topic: Level2Topic3>, <Topic: Level2Topic4>] >>> I placed the logic of the shell interaction in a custom template tag, shown below (with additional code that should remove duplicates from the list, if it … -
Why aren't my Django Postgres `ArrayAgg` members sorting?
I'm exploring the use of ArrayAgg and I don't understand why 'histidine-[13C6,15N3]' doesn't occur before 'isoleucine-[13C6,15N1]' in this example: In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] The records/rows are sorted based on the first value, which is great, but that first value isn't sorted WRT the other values in the list. For that matter, why doesn't the order of the members of the list change at all when I negate the order_by in the ArrayAgg? According to what I read, this should sort the list items. Am I blind? What am I doing wrong? In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="-tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] -
Django, docker compose, whitenoise and railways: new js files not found in production (it works in local)
I am working in a django project where I have installed and configured whitenoise to serve static files in railways. But railways is not serving or collecting my new js files. In my browser I get a 404 in settings I have configured (theoretically) whitenoise INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'captcha', 'storages', 'whitenoise.runserver_nostatic', ] 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', ] and this is where I am managing my files (I am also using amazon aws s3 to upload pdfs and other files) STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" STORAGES = { "default": { "backend": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "whitenoise.storage.CompressedStaticFilesStorage", # CompressedStaticFilesStorage }, } # Modify storage configuration if ENV_STATE == "production": SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # HIPAA-compliant Backblaze configuration AWS_ACCESS_KEY_ID = os.environ['B2_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['B2_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['B2_BUCKET_NAME'] AWS_S3_ENDPOINT_URL = os.environ['B2_ENDPOINT_URL'] AWS_S3_REGION_NAME = os.environ.get('B2_REGION_NAME', 'us-west-004') # Default region # Security settings AWS_DEFAULT_ACL = 'private' # HIPAA: Private access only #AWS_LOCATION = 'protected' # This should match your prefix AWS_S3_FILE_OVERWRITE = False AWS_S3_ADDRESSING_STYLE = 'path' AWS_QUERYSTRING_AUTH = True # Enable signed URLs for HIPAA compliance AWS_QUERYSTRING_EXPIRE = 3600 … -
How can I display a table in a template with additional category/section rows?
Have a nice day! I have a non-standard table. Which I plan to display in the template. I load the table into the template from the model. And I have additional sections - additional fields. These additional fields characterize - Category, Section, Topics. I am thinking how to display such a table from the model in the template - as shown in the picture. To additionally implement additional fields - categories or sections in the table. I have a rough idea - I have to create a transit model for exactly such a table - in which the number of rows is equal to the number of rows of the original table + plus the number of rows of category sections in addition. That is, there can be about 25 rows of the original table and + plus 6 rows - category sections. In total, the required table will have 31 rows of rows. enter image description here But how to display them in the form as in my picture - separating categories sections? models.py class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="") name_category = models.CharField(verbose_name="") name_working = models.CharField(verbose_name="") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="") value_work = models.FloatField(verbose_name="") lyudi_norma = models.IntegerField(verbose_name="") technik_norma = models.IntegerField(verbose_name="") … -
How to support multiple Google Cloud Storage buckets in a Django FileField without breaking .url resolution?
I'm using Django with django-storages and GoogleCloudStorage backend. My model has a FileField like this: raw_file_gcp = models.FileField(storage=GoogleCloudStorage(bucket_name='videos-raw')) At runtime, I copy the file to a different bucket (e.g. 'videos-retention') using the GCS Python SDK: source_blob = default_bucket.blob(name) default_bucket.copy_blob(source_blob, retention_bucket, name) After copying, I update the .name field: recording.raw_file_gcp.name = f'videos-retention/{name}' recording.save() Everything works until I restart the app. Then, when I access .url, Django tries to build the URL using the original bucket from the storage=... argument, even if the file now belongs to another bucket. It ends up generating invalid URLs like: https://storage.googleapis.com/videos-raw/https%3A/storage.cloud.google.com/videos-retention/filename.mp4 I expected Django to keep working even if the file was moved to a different bucket. After debugging, I realized that the FileField is tightly coupled to the bucket used when the model is initialized. If the file moves to another bucket, .url breaks. ChatGPT suggested removing FileField altogether, using a CharField instead, and dynamically resolving the GCS bucket + path in a custom @property using google.cloud.storage.blob.generate_signed_url(). Is there a better solution for this? How can I support multiple GCS buckets dynamically with Django FileField? -
I tried to implement custom validation error in django
I have wrote this validators.py file: from django.core.exceptions import ValidationError import os def allow_only_images_validator(value): ext = os.path.splitext(value.name)[1] print(ext) valid_extensions = ['.png', '.jpg', '.jpeg'] if not ext.lower() in valid_extensions: raise ValidationError("Unsupported file extension. Allowed extensions: " +str(valid_extensions)) This is my forms.py file: class userProfileForm(forms.ModelForm): class Meta: profile_picture = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) cover_photo = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator]) But this error is not showing in my template. The SS is here: Can anybody help me on how do I fix it? -
In Django how can I list a Queryset in one view/template generated by another view?
I'm developing a tracking system that has 2 main datasets Orders and Shipments. Focussing on Orders I want to enable users to enter any combination of field data and then display the resulting list using pagination. To achieve this I have 2 views/templates. One, search_orders, displays a form that is, essentially, a list of the majority of the dataset fields. The other, list_orders, displays a list of the selected orders. This all works fine if I just render list_orders from search_orders without any pagination but, in order to get pagination I (believe that I) need search_orders to redirect to list_orders and, so far, I've been unable to do that. Search_orders view: @login_required def search_orders(request): if request.method == 'POST' and len(request.POST) > 1: orders = Order.objects.all() msg = '' fields_selected = '' for fld in request.POST: if fld == 'orderid' and request.POST.get('orderid'): msg += f'{fld} - {request.POST.get('orderid')} and ' fields_selected = True orders = orders.filter(orderid__icontains=request.POST.get('orderid')) if fld == 'bookingtype' and request.POST.get('bookingtype'): msg += f'{fld} - {request.POST.get('bookingtype')} and ' fields_selected = True orders = orders.filter(bookingtype__icontains=request.POST.get('bookingtype')) if fld == 'shp' and request.POST.get('shp'): msg += f'{fld} - {request.POST.get('shp')} and ' fields_selected = True orders = orders.filter(shp__icontains=request.POST.get('shp')) if fld == 'con' and request.POST.get('con'): msg += …