Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weasyprint Turn Off all the Warnings
Using WeasyPrint but it is always overwhelming me with INFO, DEBUB messages. How do I turn them all off? Nothing i have tried works. (Using Django) Thanks -
Is there a way to reduce polling woth django dramtiq
I have a webapp using django hosted on render cloud platform which allows users to make api call to deepseek. These api calls sometimes take 5 minutes to respond, and doing so with async may cause issues if user connection drops. So I planned to use a Dramatiq background worker hosted on a render service too seperate to the web app. I set up redis with upstash and connected to dramtiq and it turned out it was polling redis hundreds to thousand per minute which on upstash equates to commands which equates to a high cost. So my goal is to reduce the polling to once per minute to reduce my redis commands number to reduce costs. I have tried setting up gevent too but now sure how to reduce redis polling with dramtiq and also use gevent. -
Django does not automatically create test database
I have a Django project, version - 3.2.25. The problem I'm facing is that I'm unable to create a test database, when I'm executing my tests using VScode test runner. If matters here are the pytest versions: name : pytest version : 8.2.2 description : pytest: simple powerful testing with Python required by - pytest-django requires >=5.4.0 - pytest-dotenv requires >=5.0.0 Basically, I have a test case, which uses my local database, I want to start using a virtual database, which is dynamically created when executing a test, instead of a local one. To do that, I've tried to set a Test property inside my settings.py database configuration: DATABASES = { 'default': { "NAME": "localDatabase", "ENGINE": "django.contrib.gis.db.backends.postgis", "USER": "test", "PASSWORD": "test", "HOST": "127.0.0.1", "PORT": "5432", "TEST": { "NAME": "test_local" }, }, } So inside my test case: class BillAPITests(APITestCase): def test_create_bill(self): from django.db import connection print(connection.settings_dict["NAME"] response = self.client.post(self.base_url, self.base_payload, format="json") self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) the print gives me: localDatabase instead of "test_local". As second attempt, I have tried settings up a pytest.fixture inside my conftest.py: @pytest.fixture(scope="session") def django_db_setup(): load_dotenv() settings.DATABASES["default"] = { "NAME": "test_local", "ENGINE": "django.contrib.gis.db.backends.postgis", "USER": "test", "PASSWORD": "test", "HOST": "127.0.0.1", "PORT": "5432", } Still the same output... I have … -
Create Action Button in Open edx Admin panel using tutor plugins
I created and enabled a tutor plugin successfully using this command cookiecutter https://github.com/overhangio/cookiecutter-tutor-plugin.git How would I use this plugin to implement Admin Action Button: I have a folder adminUser with 2 files init.py (from . import admin) and admin.py see content below: from django.contrib import admin from django.contrib.auth.models import User @admin.action(description="Mark selected Users as inactive") def mark_users_inactive(modeladmin, request, queryset): queryset.update(is_active=False) modeladmin.message_user(request, f"{queryset.count()} users marked as inactive.") admin.site.unregister(User) @admin.register(User) class CustomUserAdmin(admin.ModelAdmin): list_display = ("username", "email", "first_name", "last_name", "is_staff", "is_active") actions = [mark_users_inactive] I added the lines below to the plugin.py: PLUGIN_ROOT = Path(__file__).parent.parent.resolve() hooks.Filters.COMPOSE_MOUNTS.add_item(("lms", (str(PLUGIN_ROOT / "adminAction"), "/openedx/edx-platform/adminAction"))) hooks.Filters.COMPOSE_MOUNTS.add_item(("cms", (str(PLUGIN_ROOT / "adminAction"), "/openedx/edx-platform/adminAction"))) Added patches/openedx-lms-env with INSTALLED_APPS += ["adminAction"] Added recursive-include adminAction * in ./MANIFEST.in In pyproject.toml Added include = ["adminAction"] under [tool.hatch.build.targets.wheel] Updated include = [ "/tutoradmin", "/adminAction", ".hatch_build.py"] under [tool.hatch.build.targets.sdist] Yet the Action Button is not visible. Please what am I doing wrong? -
How to make scrollable list of buttons
Needed to make scrollable list of buttons in the left part of the screen. But the scrollbar in child div, even forced by overflow: scroll is not working. Read about removing overflow from parent objects, but without success. Left only body parent object for simplifying the code fragments below base.html </header> <body> {% block content %} {% endblock %} </body> <html> cities.html {% extends "base.html" %} {% block content %} <div class="scrollbox"> {% for city in cities %} <form action="{% url 'city_detail' %}" method="post"> {% csrf_token %} <input type="hidden" name="city_id" value={{ city.id }}> <button type="submit">{{ city.name }} </button> </form> {% endfor %} <p> Censored...</p> <!-- added for testing ~100+ - enough for make scrollbar workable by text only - no success --> <p> Censored...</p> </div> {% endblock %} CSS @import url(//fonts.googleapis.com/css?family=Muli); body { margin:0; padding:0; /* with overflow hidden main scrollbar not shown, but forced scrollbar in child div not working and the data is cut with value auto scroll shown for whole content, remainin not working for child div */ overflow: auto; font-family:helvetica, sans-serif; } .scrollbox { min-height: 90vh; border: 2px solid; /* for being sure, that no syntax errors in names, etc - border shown - OK */ … -
Search filter not working Vue.js/Django(DRF)
I'm learning DRF from video, I can't figure out how to get the query parameter from vue.js in django so that the filter works. Github of the project author: Django: https://github.com/SteinOveHelset/djackets_django Vue.js: https://github.com/SteinOveHelset/djackets_vue Link to video: https://www.youtube.com/watch?v=Yg5zkd9nm6w&t=4867s I don't understand anything about vue.js, I'm just repeating the code. On the vue.js side, the page doesn't change, but there are no errors either. There are errors on the django side: "GET /api/v1/products/search/ HTTP/1.1" 405 5711 "POST /api/v1/products/search/ HTTP/1.1" 400 5714 views.py @api_view(['POST']) def search(request): query = request.data.get('query', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) serializer = ProductSerializer(products, many=True) return Response(serializer.data) else: return Response({"products": []}) App.vue <form method="get" action="/search"> <div class="field has-addons"> <div class="control"> <input type="search" class="input" placeholder="What are you looking for?" name="query"> </div> <div class="control"> <button class="button is-success"> <span class="icon"> <i class="fas fa-search"></i> </span> </button> </div> </div> </form> Search.vue <template> <div class="page-search"> <div class="columns is-multiline"> <div class="column is-12"> <h1 class="title">Search</h1> <h2 class="is-size-5 has-text-grey">Search term: "{{ query }}"</h2> </div> <ProductBox v-for="product in products" v-bind:key="product.id" v-bind:product="product" /> </div> </div> </template> <script> import axios from 'axios' import ProductBox from '@/components/ProductBox.vue' export default { name: 'Search', components: { ProductBox }, data() { return { products: [], query: '' } }, mounted() { document.title = … -
Using a model property (list of dictionaries) as an input to django's format_html_join() yields KeyError
I am attempting to use Django's format_html_join() util to return an html formatted version history for one of my models. But I cannot get format_html_join() to accept my list of dictionaries. Here is what the documentation suggests: format_html_join( "\n", '<li data-id="{id}">{id} {title}</li>', ({"id": b.id, "title": b.title} for b in books), ) That third argument is intended to be: args_generator should be an iterator that yields arguments to pass to format_html(), either sequences of positional arguments or mappings of keyword arguments. I have tried different ways to get this to work and I'm not getting it, so I'm asking for help. I thought a list of dictionaries is iterable. I'm also thinking there has to be a way to use a list of dictionaries in a util that is expecting a list of dictionaries without having to re-create the list of dictionaries. Here is the model method I have to get the version history: @property # I have tried this as a property and not as a property, neither works def get_version_history(self): versions = Version.objects.get_for_object(self) version_history = [] for version in versions: history_fields = version.field_dict hdict = {"question": history_fields['question'], "answer": history_fields['answer'], "user": version.revision.user.username, "timestamp": version.revision.date_created.strftime("%Y-%m-%d %H:%M"), } version_history.append(hdict) return version_history That … -
Plotly chart not working correcly with HTMX call
I've added HTMX to my Django project, and after that my plotly chart started glitching. I generate HTML for the chart with: def get_chart(f, power, resolution): import pandas as pd yaxis_title = "Power, %" try: df = pd.read_csv( os.path.join(settings.MEDIA_ROOT, f), compression="zip", sep=" ", header=None, names=["Date", "Val"], ) if power and power != 100: df.Val = df.Val.apply(lambda x: x * power / 100) yaxis_title = "Power, kW" fig = go.Figure( data=[ go.Scatter( x=df["Date"], y=df["Val"], ), ], ) fig.update_layout( title="", yaxis_title=yaxis_title, hovermode="x unified", width=resolution.value[0], height=resolution.value[1], margin=dict( l=4, r=4, b=4, t=40, pad=4, ), ) fig.update_yaxes( fixedrange=False, ) return fig.to_html(full_html=False, div_id="rtv-chart") except (OSError, ValueError, BadZipFile) as e: print(e) return None Which I send back with a view: def chart(request, pk): obj = RtvLog.objects.get(id=pk) if res := request.GET.get("size"): chart = get_chart(obj.log.file.name, obj.power, Resolution[res]) else: chart = get_chart(obj.log.file.name, obj.power, Resolution.SVGA) if chart: return HttpResponse(chart, content_type="text/html") return HttpResponse(status=404) And then render in a template: <div class="flex gap-4 w-fit"> <div hx-get="{% url 'tools:get_chart' object.id %}" hx-trigger="load once, change from:#size" hx-include="#size" hx-indicator="#chart-indicator" hx-target="this"> <div class="htmx-indicator" id="chart-indicator">{% include "block-spinner.html" %}</div> </div> <fieldset id="size"> <legend>Select chart size:</legend> {% for size in sizes %} <div> <input type="radio" id="size_{{ size }}" name="size" value="{{ size }}" {% if forloop.counter == 2 %}checked{% endif %} … -
How to add a relationship to a GeneratedField in Django
Context I have a model: class Article(models.Model): id = models.UUIDField(default=uuid4, editable=False, unique=True, primary_key=True) paper_id: UUID | None paper = models.ForeignKey["Paper"]( "Paper", on_delete=models.CASCADE, related_name="articles", null=True, blank=True, ) website_id: UUID | None website = models.ForeignKey["Website"]( "Website", on_delete=models.CASCADE, related_name="articles", null=True, blank=True, ) I then have a view that unifies Paper and Website: class Source(pg.View): sql = """ SELECT ... FROM papers UNION ALL SELECT ... FROM websites ; """ id = models.UUIDField(unique=True, primary_key=True) # ... Question I'd like to make it so from a Source model I can get the articles (e.g. source.articles.all()). How can I do that? What have I tried? I've tried to add this field to Article: source_id = models.GeneratedField( expression=Coalesce(F("paper_id"), F("website_id")), output_field=models.UUIDField(), db_persist=False, ) source = models.ForeignKey["Source"]( "Source", on_delete=models.DO_NOTHING, related_name="articles", db_column="source_id", to_field="id", null=True, editable=False, ) But when creating the migration I get: (models.E006) The field 'source' clashes with the field 'source_id' from model 'Article'. -
502 Bad Gateway Nginx | Django | Gunicorn on Load Balancer
I have an AWS Elastic Load Balancer (ELB) and listeners which redirect to port 80 internally (certificates and SSL termination at the ELB). I'm running nginx on the EC2 instances, along with php, gunicorn and django/python. The cluster is being set up to host multiple domain names with distinct websites/apps for each. External http/https requests work fine for html and php, returning the pages. For django requests using sockets I'm getting a 502 Bad Gateway error externally, but internally via curl (eg. curl --unix-socket /tmp/gunicorn_.sock http:///app/) it works fine. Externally https:///test (simple Nginx endpoint) works fine None of the logs I can find show errors. eg: [2025-07-31 00:05:07 +0000] [776767] [INFO] Handling signal: term [2025-07-31 00:05:07 +0000] [776771] [INFO] Worker exiting (pid: 776771) [2025-07-31 00:05:07 +0000] [776769] [INFO] Worker exiting (pid: 776769) [2025-07-31 00:05:07 +0000] [776768] [INFO] Worker exiting (pid: 776768) [2025-07-31 00:05:08 +0000] [778670] [INFO] Starting gunicorn 23.0.0 [2025-07-31 00:05:08 +0000] [778670] [INFO] Listening at: unix:/tmp/gunicorn_<domain>.sock (778670) [2025-07-31 00:05:08 +0000] [778670] [INFO] Using worker: sync [2025-07-31 00:05:08 +0000] [778672] [INFO] Booting worker with pid: 778672 [2025-07-31 00:05:08 +0000] [778673] [INFO] Booting worker with pid: 778673 [2025-07-31 00:05:08 +0000] [778674] [INFO] Booting worker with pid: 778674 My server conf server … -
Starting django with python manage.py runserver and getting ModuleNotFoundError: No module named '_msi'
django was working fine my venv got corrupted and I rebuilt it from requirements.txt now getting File "C:\Users\PC\OneDrive\Documents\GitHub\DoseV3Master\venv\Lib\site-packages\msilib_init_.py", line 3, in from _msi import * ModuleNotFoundError: No module named '_msi' went to pypi and got the installer pip install python-msi to noeffect. Then pip install pymsilib also no effect. -
I can't Go To Definition for pytest fixtures in Cursor (VSCode)
I am using Cursor. I cannot command-click into fixtures injected as parameters in my pytests. Command-clicking to any other variable, function, class works fine. I am working in a Django Ninja project. @pytest.mark.django_db def test_deleting_an_already_inactive_channel_raises_error(mock_auth, client, client_headers, user, channel): channel.active = False channel.save() url = reverse("roon:channel", kwargs={"channel_id": channel.id}) response = client.delete(url, content_type="application/json", headers=client_headers(user)) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY In the above example, I cannot click into mock_auth, client, client_headers etc. Here is my vscode settings.json: { "python.testing.pytestEnabled": true, "python.testing.pytestArgs": ["--import-mode=importlib", "--no-cov"] } Here is my pyproject.toml: [tool.pytest.ini_options] minversion = "7.0" #Pytest to have verbose outputs #Pytest-xdist automatically determines number of workers based on cpu#Output a summary of all, except passes #Pytest report stats - Failures + Skipped #Pytest-cov to report coverage for library #Pytest-cov to use pyproject.toml file for additional coverage config #Pytest-cov outputs coverage to stdout #Pytest-cov fails if the coverage falls under the value #Pytest-cov generates an HTML report in /test-results #Pytest-cov generates an XML report in /test-results addopts = ''' -vv -n auto -ra -m "not (deprecated or integration)" --cov=api --cov-config pyproject.toml --cov-report term-missing --cov-fail-under=60 --cov-report html --cov-report xml --durations=10 -s ''' markers = [ "integration: marks tests for integration environment (deselect with '-m \"not integration\"')", "slow: marks … -
What could cause a Django webpage rendering on main domain but not subdomain and localhost?
I’m trying to solve an issue with djangoproject.com. The footer on the bottom right has a “Corporate Membership” link under “Support Us”. The “Corporate Membership” link works when the url is https://www.djangoproject.com/foundation/corporate-membership/%E2%80%9D but not in case of https://docs.djangoproject.com/foundation/corporate-membership/%E2%80%9D or https://dashboard.djangoproject.com/foundation/corporate-membership/%E2%80%9D. It also raises a Page not Found (404) error on the development server, like so I searched the repo and couldn't find any template for this link, if the template doesn't exist how is it rendering in production? urls/www.py from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.contenttypes import views as contenttypes_views from django.contrib.flatpages.sitemaps import FlatPageSitemap from django.contrib.sitemaps import views as sitemap_views from django.urls import include, path, re_path from django.views.decorators.cache import cache_page from django.views.generic import RedirectView, TemplateView from django.views.static import serve from accounts import views as account_views from aggregator.feeds import CommunityAggregatorFeed, CommunityAggregatorFirehoseFeed from blog.feeds import WeblogEntryFeed from blog.sitemaps import WeblogSitemap from foundation.feeds import FoundationMinutesFeed from foundation.views import CoreDevelopers admin.autodiscover() sitemaps = { "weblog": WeblogSitemap, "flatpages": FlatPageSitemap, } urlpatterns = [ path("", TemplateView.as_view(template_name="homepage.html"), name="homepage"), path( "start/overview/", TemplateView.as_view(template_name="overview.html"), name="overview", ), path("start/", TemplateView.as_view(template_name="start.html"), name="start"), # to work around a permanent redirect stored in the db that existed # before the redesign: path("overview/", RedirectView.as_view(url="/start/overview/", permanent=False)), path("accounts/", include("accounts.urls")), … -
How can I trigger automatic actions when a model field (e.g. date) reaches a specific time like 5 days, weekly, or yearly?
I’m working on a Django-based app where developers can connect users to their apps using an account number. Once connected, a Subscription model is created with fields like user, plan, is_active, and next_billing_date. The next_billing_date depends on the plan type (weekly, monthly, yearly, etc.). I want to automatically take some action (e.g., disable is_active or charge again) when the next_billing_date is reached. This includes: Deactivating expired subscriptions Or triggering recurring billing based on subscription cycle (e.g. Jan 1, 2025 → Jan 1, 2026 for yearly, or weekly for others) I already store the next billing date like this: next_billing_date = timezone.now().date() + timedelta(days=30) # For monthly plans I was trying to use signals to handle things like automatically charging users after 7 days or ending a subscription after 1 month. But I realized that Django signals only work when a model is saved, updated, or deleted, not based on time passing. This means if I want something to happen exactly 7 days after a user subscribes, a signal won’t help unless something else triggers it (like the model being saved again). So even if the subscription is about to expire, Django won’t do anything automatically unless some code updates that … -
How can I secure my Dockerized Django + PostgreSQL app in production on a VPS using Nginx?
I’m using Django and PostgreSQL for my web project, which I’ve containerized using Docker. I run it on a VPS and serve it with Nginx (running outside Docker). I'm concerned about the security of my PostgreSQL database and want to make sure it's properly locked down. Specifically, I want to understand best practices to protect the database when: Docker containers are running in detached mode The PostgreSQL service is inside Docker Nginx is acting as the web entry point from the host My questions: How can I ensure my PostgreSQL container is not exposed to the public internet? What are Docker and PostgreSQL-specific security improvements I can apply? Are there any changes I should make in the following Dockerfile or docker-compose-prod.yml? My current Dockerfile FROM python:3.x.x # Set environment variables ENV PYTHONDONTWRITEBYTECODE=x ENV PYTHONUNBUFFERED=x WORKDIR /src # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ build-essential \ && rm -rf /var/lib/apt/lists/* # Install Poetry RUN curl -sSL https://install.python-poetry.org | python3 - && \ export PATH="/root/.local/bin:$PATH" # Add this line to make sure Poetry is in the PATH for subsequent commands ENV PATH="/root/.local/bin:$PATH" COPY pyproject.toml poetry.lock* ./ # # Install dependencies RUN poetry config virtualenvs.create … -
Unable to properly render ModelSelect2Multiple in modal window
i have a Book model that has a authors field which is a ManyToMany field to Author model. I'm using django-autocomplete-light package to render a select2 widget in my templates that will allow me to select more than one author when creating new books. (Using ModelSelect2Multiple) So the field renders OK in a regular html page. But when i try to render the same exact form in a DaisyUI modal window, the dropdown menu that it should open will be opened in the back of the modal window (like i can see it is being displayed behind the modal window). Here is my form: class BookForm(forms.ModelForm): class Meta: model = Book fields = ( 'title', 'authors', ) widgets = { 'authors': autocomplete.ModelSelect2Multiple( url=reverse_lazy('shop:authors-autocomplete') ) } Here is the modal container (followed the documentation from django-autocomplete-light): {% load static %} <dialog id="new_book_modal_container" class="modal"> <div class="modal-box"> <div id="response"> <strong>form will be placed here</strong> </div> </div> </dialog> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} Here is the form template: {% load static %} <div> {% if form %} <form> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary btn-sm"> Submit </button> </form> {% endif %} </div> Using htmx, i open … -
Uppy with DO Storeages on Django
I have been fighting with this for hours. I can not get Uppy AWS to work. I am using DigitalOcean Storage. Here is the html. (part is Github Copilot) <script type="module"> import {Uppy, Dashboard, AwsS3} from "https://releases.transloadit.com/uppy/v4.13.3/uppy.min.mjs" const uppy = new Uppy() uppy.use(Dashboard, {target: '#uppy', inline: true}) .use(AwsS3, { getUploadParameters (file, options) { return fetch('/upload/uppy_s3').then((response) => response.json()) }, }) </script> Here is the backend view. client = boto3.client('s3', region_name='sgp1', endpoint_url='https://sgp1.digitaloceanspaces.com', aws_access_key_id=SPACES_KEY, aws_secret_access_key=SPACES_SECRET, config=Config(s3={'addressing_style': 'virtual'}), ) url = client.generate_presigned_url( ClientMethod='get_object', Params={ "Bucket": "mysite-bucket", "Key": "uppyfile.pdf", }, ExpiresIn=3600 ) return { "method": "PUT", "url": url, "headers": { "content-type": "application/pdf" }, } I have been working on this for hours and tried many combinations. right now I am getting: AttributeError: 'dict' object has no attribute 'status_code' I am not a javascript person so I am sure my errors are obvious to most of you. Most of this is via Copilot. the videos on youtube are outdated and don't work. Thank you so much. -
Django Admin ask for login on every click
Working on a Django project deployed on AWS. In production, I'm facing a session-related issue: When I open the Django admin site (/admin) and log in, everything works smoothly. But if I open the user site (/) in the same browser window and log in there, the admin gets logged out — which is expected behavior, so no complaints there. But here's the twist: Even after closing the user site tab, when I go back to the admin site and log in again, Django lets me into the admin dashboard — only to forget me immediately. Every time I try to do literally anything (open a model, add a record, even breathe)... Django hits me with: “Oh hey 👋 just checking — who are you again?” Then it redirects me right back to the login page. I log in. I click something. Back to login. I log in again. I blink. Login page. Again. It’s like Django has the memory of a goldfish 🐠. -
Python Wand: MagickReadImage returns false, but did not raise ImageMagick exception
I've got some long-standing code in a Django code base that reads in a PDF and uses Wand to take a screenshot of the first page of the PDF, which is then displayed on the website. We recently migrated servers (an upgrade from Ubuntu 22 LTS to 24 LTS), and something broke, and I can't for the life of me figure it out. First, some potentially useful information: OS: Ubuntu 24 LTS Python 3.12.3 Django 5.2.4 Wand 0.6.13 Web server: nginx 1.24.0 gunicorn version: 23.0.0 We are not using Docker. This Django app is running directly on the server with a local virtual environment. The PDF-to-PNG code is on the admin side of the web app. Here's the heart of it: with Image(filename=pdf_location) as pdf: with Image(pdf.sequence[0]) as first_page_pdf: with first_page_pdf.convert('png') as first_page_png: first_page_png.background_color = Color('white') first_page_png.alpha_channel = 'remove' return first_page_png.make_blob() When I upload a PDF to the admin site for processing, I'm getting this error: MagickReadImage returns false, but did not raise ImageMagick exception. This can occur when a delegate is missing, or returns EXIT_SUCCESS without generating a raster. I have tried everything I can think of after a ton of searching, but nothing is working: I do have … -
JavaScript Django default scaling using extends index
I'm using Django's template inheritance (extends) in every page of the app. The current design looks too zoomed out, and I want to adjust the default scaling through my index.html, but it didn't work. I also tried using custom CSS, but it still doesn't fix the issue. Does anyone have an idea how I can adjust the default scaling properly? I have this in my index.html <meta name="viewport" content="width=450, initial-scale=0.6, user-scalable=yes, minimum-scale=0.6, maximum-scale=0.6" /> -
Filter Django RangeField by comparing to a point, not to another range
The PostgreSQL specific model fields docs are very specific about how to compare one RangeField to another range. But how do you compare a range to a single point? For example, if I've got a model with valid_range=DateTimeRangeField, and I want to find all instances which are no longer valid, I need to do something like: from django.utils import timezone as tz MyProduct.objects.filter(valid_range__lt=tz.now()) But this isn't allowed. I thought I could use fully_lt but that's not allowed with a particular date either. How do I filter a DateTimeRangeField to find instances whose ranges ended before a certain datetime? -
502 Bad Gateway on AWS ELB with Nginx + Django + Gunicorn
Summary of Issue: 502 Bad Gateway from ELB to Django app behind Nginx + Gunicorn on EC2 Environment: Hi, I wonder if anyone can assist. I've been banging my head against a wall for over a week now, I've tried two different AI's and reviewed everything I can find here and on AWS. I have an Elastic Load Balancer (Application) and Auto Scaling Group. Everything is set up in line with best practice, html and php pages are served up fine. However django is not served to the public side of the ELB, it returns a 502 Bad Gateway. • AWS Elastic Load Balancer (ELB) in front of EC2 instance • ELB terminates HTTPS, forwards HTTP (port 80) to Nginx on EC2 • Nginx configured as reverse proxy forwarding /app/ requests to Gunicorn via Unix socket • SELinux is set as Permissible • Django app served by Gunicorn, running on EC2 • Nginx version 1.28.0, Gunicorn serving Django app on Unix socket /tmp/gunicorn_.sock • Django app uses virtual environment with dependencies installed per deployment script Observed Behavior: • curl -vk https:///test (simple Nginx endpoint) returns HTTP 200 OK correctly • curl --unix-socket /tmp/gunicorn_.sock http:///app/ returns HTTP 200 OK correctly — … -
How to use pytes fixtures in single Django TestCase testfunction
Test yields TypeError: test() missing 1 required positional argument: 'fix' from django.test import TestCase import pytest @pytest.fixture def fix(): return "x" class QueryTestCase(TestCase): def test(self, fix): print(fix) An almost similar case exists but I want the fixture to be used only in that particular test but not the class -
importing files twice from multiple files
imagine i have a "first.py" file with some code in it , and then i import it in another python file called "secend.py" then i import the "secend.py" file & the "first.py" into "third.py" file ,, Will this cause an performance problems? (For example, a file is imported twice inside another file .. ?) I always run into this problem in Django projects.(if it is a problem) for example i have my models file and i import the models file into serialazers file and then i import both models & serializers file into views file maybe im anot the best person at drawing things but there is a kinda stupid schematic that shows what im talking about! : -
Where are these PydanticDeprecatedSince20 and RemovedInDjango60Warning warnings coming from?
I am getting the following output in my warnings summary: venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: 15 warnings /Users/darshankalola/Desktop/roon-be/roon-doctor-service/.venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: PydanticDeprecatedSince20: Support for class-based `config` is deprecated, use ConfigDict instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/ warnings.warn(DEPRECATION_MESSAGE, DeprecationWarning) .venv/lib/python3.11/site-packages/django/db/models/fields/__init__.py:1148: 15 warnings /Users/darshankalola/Desktop/roon-be/roon-doctor-service/.venv/lib/python3.11/site-packages/django/db/models/fields/__init__.py:1148: RemovedInDjango60Warning: The default scheme will be changed from 'http' to 'https' in Django 6.0. Pass the forms.URLField.assume_scheme argument to silence this warning, or set the FORMS_URLFIELD_ASSUME_HTTPS transitional setting to True to opt into using 'https' as the new default scheme. return form_class(**defaults) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html Results (7.89s): 45 passed I have searched and ensure that none of my tests are producing these warnings. In fact I have no idea where they are coming from. I have updated required packages to their latest versions, and have corrected instances of deprecated functionality.