Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Heroku django-tenant attributeerror: 'databasewrapper' object has no attribute 'schema_name'
I'm migrating my development to django-tenants, I didn´t had any issues doing it on my local, but when I push my changes to the prod environment in Heroku, I'm getting the following error: attributeerror: 'databasewrapper' object has no attribute 'schema_name' Procfile web: gunicorn tlgrmbot.wsgi Database settings: DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': os.environ.get('DB_NAME_BOT'), 'USER': os.environ.get('DB_USER_BOT'), 'PASSWORD': os.environ.get('DB_PWD_BOT'), 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "tenant_manager.Tenant" TENANT_DOMAIN_MODEL = "tenant_manager.Domain" and I have this toggle here for prod environment: if mode == 'webhook': DATABASES['default'] = dj_database_url.config( conn_max_age=600, ssl_require=True) The issue appears when I try to make migrations in the prod environment in Heroku Error log: <module 'os' (frozen)> Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django_tenants/management/commands/migrate_schemas.py", line 66, in handle executor.run_migrations(tenants=[self.PUBLIC_SCHEMA_NAME]) File "/app/.heroku/python/lib/python3.11/site-packages/django_tenants/migration_executors/standard.py", line 11, in run_migrations run_migrations(self.args, self.options, self.codename, self.PUBLIC_SCHEMA_NAME) File "/app/.heroku/python/lib/python3.11/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations connection.set_schema(schema_name, tenant_type=tenant_type, include_public=False) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'DatabaseWrapper' object has no attribute 'set_schema' -
What's the best way to handle valueless attributes in Django templates?
I'm looking for a cleaner way to conditionally add valueless HTML attributes, like disabled, in a Django template. For example, in the code snippet below, the {% if %} tag is embedded directly inside the <button> tag, which I find makes the code harder to read. <button type="submit" id="prev-page-btn" class="btn btn-secondary w-50" name="prev-page-btn" {% if not page_obj.has_previous %}disabled{% endif %}> Previous </button> Is there a more elegant solution for this? I'd like to avoid duplicating the entire <button> block just to control the presence of the disabled attribute. -
'querystring' received too many positional arguments when passed a QueryDict
I'm using Django 5.2 and I can't get my head around the following issue: In my view, I have something like this: removal_qs = request.GET.copy() # contains teams=1&teams=2 removal_qs.setlist('teams', [1]) Debugging shows: In [3]: type(removal_qs) Out[3]: django.http.request.QueryDict But when I try to use this with the {% querystring %} tag in a template, like so <a href="{{ request.path }}{% querystring qs %}">x</a> I get the error 'querystring' received too many positional arguments. The documentation for the querystring template tag specifically says that This tag requires a QueryDict instance, which defaults to request.GET if none is provided. So where am I doing this wrong? -
Heroku not finding my static files with Django
Hello I'm on a fullstack course with the Code Instiute and both me and technical support have been stumped on this issiue: After deploying on Heroku no css or js loads or runs. error from chrome inspect console log: turnpenny-fry-syndrome-98cd38841f84.herokuapp.com/:1 Refused to apply style from 'https://turnpenny-fry-syndrome-98cd38841f84.herokuapp.com/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. css is linked in html like so: <link rel="stylesheet" href="{% static 'css/style.css' %}"> settings file: STATIC_URL = "static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static" ),] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") Relative file path of my css file: static\css\style.css And Debug is always set to False when deploying. Seemingly the error messages show the right path for the files both in vs code and on github, seems like now its Heroku not reading from github correctly??? Have grone through Django documentation: https://docs.djangoproject.com/en/4.2/ref/settings/#static-url https://docs.djangoproject.com/en/4.2/ref/contrib/staticfiles/#django-admin-findstatic both me and support staff on my course have many times checked my settings file, .python-verion file, base.html links and commented out js link so i can just focus on css first also, I checked config vars and they appear all correct. -
Is using Google Cloud Tasks to invoke an internal Django endpoint effectively asynchronous (even under WSGI)?
I'm running a Django application on Google Cloud Run using the default WSGI-based setup (e.g., Gunicorn/ runserver for local dev). To avoid blocking during long-running operations like third-party API calls, I'm planning to use Google Cloud Tasks. Current design: A request comes in to a Django endpoint (e.g., a webhook or ping from an external service) Instead of processing the request inline, I enqueue a Cloud Task That task posts to another Django endpoint within the same service, which performs the third-party API call using data passed in the task payload This means: I'm not offloading the work to a separate Cloud Run service The fetch logic is still part of the same Django service/container, just decoupled by the task My question: Does this setup allow the third-party call to be effectively asynchronous (i.e., non-blocking to the original request), despite using WSGI and not ASGI or Celery? When searching around, I mostly see articles and examples where Cloud Tasks are used to call a separate Cloud Run service, not another internal route in the same app. Is this internal invocation pattern valid and scalable under WSGI, or are there caveats I should be aware of? -
Django multi-app authentication: sharing custom token validation and permissions across separate codebases
I'm building a multi-platform system where I have one central authentication service (let's call it "Auth") and multiple other Django applications (App1, App2, App3) that need to authenticate users with custom tokens and permissions. Current Setup: Auth service: Handles user registration, login, token management App1, App2, App3: Separate Django projects with their own database and business logic All apps need to validate users authenticated through the Auth service Authentication Flow: User logs in through Auth service → receives token User makes requests to App1/App2/App3 with that token App1/App2/App3 need to validate the token and get user data Authentication Model: class AuthToken(models.Model): token = models.CharField(max_length=48, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) platform = models.ForeignKey(Platform, on_delete=models.CASCADE) expires_at = models.DateTimeField(null=True, blank=True) is_revoked = models.BooleanField(default=False) # other fields (ip, device_id, device_name, etc...) Token Configuration: Settings.py # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'path.to.authentication.AuthTokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } Authentication Class # path/to/AuthTokenAuthentication.py class AuthTokenAuthentication(BaseAuthentication): """ Simple, clean AuthToken authentication. """ def authenticate(self, request): # Get Authorization header auth_header = request.META.get('HTTP_AUTHORIZATION') if not auth_header or not auth_header.startswith('Bearer '): return None # No token provided # rest of my code The Problem: App1, App2, App3 need to use the same custom AuthTokenAuthentication and permission classes, but … -
Refresh token being passed in response body in registration but not login in Django
I am using the Django REST Framework with dj-rest-auth and django-allauth for authentication and authorisation with JWTs. From what I have heard, using HTTP-only cookies to store the tokens is a secure approach where the access token is passed in the response body but the refresh token is passed to the browser as a cookie. The default login endpoint works this way, returning the access token in the response body and returning the access and refresh tokens as HTTP-only cookies as well as a csrftoken and sessionid. However, the signup endpoint doesn't exhibit the same behaviour, it returns both access and refresh tokens in the response body and returns neither as a cookie, but does return these cookies: messages, csrftoken, sessionid. Does anyone know why this might be happening and how I could get registration to behave the same way as login? Here are the relevant parts of my settings.py: REST_AUTH = { "USE_JWT": True, "JWT_AUTH_COOKIE": "access-tkk", "JWT_AUTH_REFRESH_COOKIE": "refresh-tkk", # "JWT_AUTH_SECURE": True, # Use secure cookies in production for HTTPS only "JWT_AUTH_HTTPONLY": True, # Secure HTTP-only cookies "REGISTER_SERIALIZER": "authentication.serializers.CustomRegisterSerializer", "USER_DETAILS_SERIALIZER": "authentication.serializers.CustomUserDetailsSerializer", } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15), # Short-lived access token "REFRESH_TOKEN_LIFETIME": timedelta(days=14), # Longer-lived refresh token "ROTATE_REFRESH_TOKENS": True, # … -
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 🐠.