Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot find settings module in mod_wsgi (Apache2 on Ubuntu with django)
I am serving a Python app using Django through an Apache2 server. I have the wsgi.py file in a directory home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py I have a venv in home/peter/django-apps/anaaccess/anaaccess/myenv into which I have installed mod_wsgi and django, etc. I have put these lines into apache.conf to set up this venv to handle the python: LoadModule wsgi_module "/home/peter/django-apps/anaaccess/anaaccess/myenv/lib/python3.12/site-packages/mod_wsgi/server/mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so" WSGIPythonHome "/home/peter/django-apps/anaaccess/anaaccess/myenv" I call the application in the virtual host section of the Apache2 configuration: WSGIScriptAlias /bayeux /home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py <Directory /home/peter/django-apps/anaaccess/anaaccess/ana_access> <Files wsgi.py> Require all granted </Files> </Directory> In the wsgi.py file I call the application as follows: import os import django from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ana_access.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "ana_access.settings" application = get_wsgi_application() All seems to start fine. Apache finds and loads the mod_wsgi module, finds the wsgi.py file, and finds the os and django modules. But it fails to find the settings file, with this error: mod_wsgi (pid=98141): Failed to exec Python script file '/home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py'., referer: http://109.123.108.170/ mod_wsgi (pid=98141): Exception occurred processing WSGI script '/home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py'., referer: http://109.123.108.170/ Traceback (most recent call last):, referer: http://109.123.108.170/ File "/home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py", line 19, in <module>, referer: http://109.123.108.170/ application = get_wsgi_application(), referer: http://109.123.108.170/ ^^^^^^^^^^^^^^^^^^^^^^, referer: http://109.123.108.170/ File "/home/peter/django-apps/anaaccess/anaaccess/myenv/lib/python3.12/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application, referer: http://109.123.108.170/ django.setup(set_prefix=False), referer: http://109.123.108.170/ File "/home/peter/django-apps/anaaccess/anaaccess/myenv/lib/python3.12/site-packages/django/__init__.py", line … -
In Django form, set ModelChoiceField selection when form renders
I have been tasked with making changes to a django project's form. On this form is a ModelChoiceField. The customer request is to populate this field with the text of a value in its selection list when that value is supplied via the URL selected by the customer. The view and form are instantiated when the system starts. The user, via magic I don't need to know, references a URL that will include three values. The first, existing, value is an ID that is used to populate many of the fields. The task is to take two more values and populate two more fields. One is just text and that I have accomplished. The second is the text of a value within the selection list of the ModelChoiceField. This value, when supplied in the URL, should be displayed as the selected value. I have Googled extensively and everything I have found speaks of setting the value in the init method. This won't work because, as said above, the form and view are created at system startup and the values supplied at runtime are used to render the form. I have tried simply setting the value in the data structure that … -
Solution to not split logic in django to solve N+1 queries
Here are some of my models: class CustomUser(AbstractUser): def correct_date(self, date=None): res = self.dates.order_by("date").all() if not len(res): return None return res[len(res) - 1] class Date(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="dates") date = models.DateField(auto_now_add=True) To fix N+1 queries I need to extract the order_by in the view with a Prefetch: queryset = Project.objects.prefetch_related( Prefetch( "user__dates", queryset=Date.objects.order_by('date') ), ) and remove the order_by in my correct_date method. The problem here is that correct_date depends on the order_by in order to retrieve the last date. But the order_by is in an other file. That could leeds to issues for the ones using the code after. Is there any other solutions than: Keeping the code as it is with a comment # needs to be used with an order_by('date') before Using a service to handle all that logic Checking in the correct_date method if it was called with an order_by before, and throwing an error or apply order_by if it wasn't -
Django send_mail() / EmailMessage with Gmail SMTP has 4-minute delay for new email recipients
I’m facing a consistent email delivery delay when using Django’s built-in send_mail() or EmailMessage functions with Gmail SMTP. 🔧Setup: - Backend: Django (tested with both send_mail() and EmailMessage) - SMTP: smtp.gmail.com with App Passwords - Recipients: New or first-time email addresses (e.g., new Gmail or company emails) - Sender: Personal Gmail account using App Password (not Google Workspace) - Observation: - Emails show up instantly in the sender's Sent folder. - Recipient receives the email after ~4 minutes delay, only on the first send. - On re-sending to the same recipient, delivery is almost instant. 📌 This is especially problematic for: Sign-up confirmation, OTP delivery, Real-time alerts or notifications ❌ What I’ve Tried: - Tested both old and new Gmail accounts. - Created new and old App Passwords. - Sent using both send_mail() and EmailMessage. - Tried different recipient domains (Gmail, Outlook, work domains, etc.). - Verified there’s no error or SMTP failure — just delay. 🧠 Additional Notes: - The issue does not occur for known recipients. - SMTP works fine; it's the delivery to new recipients that lags. - Server is configured correctly, no IPv6 hangups. - Delay seems similar to what Gmail does with anti-phishing checks, but … -
Django inline formset won't save form appended via JS
I'm trying to create page where "parent" and related object may be updated. Due to some specific business logic "child" form has specific couple of fields where only one of them may be selected. So when option selected JS issues a GET request to get the updated form. The problem is: the form being fetched with initial values and when formset.save() being called the form's cleaned_data turns empty {}. The things I've checked: Formset.management_form in tact; All prefixes correct; Formset.data looks good; If I change any data of form inserted dynamically and submit it saves as expected. So the problem seems to be how formsets utilize form.has_changed() logic. This won't work as well: class CustomFormset(forms.BaseInlineFormSet): for form in self.forms: form.empty_permitted = False A bit of code may be helpful: class ParentForm(forms.ModelForm): title = forms.CharField() description = forms.CharField() class ChildForm(forms.ModelForm): item = forms.ModelChoiceField() item_type = forms.ModelChoiceField() # ---------- One of these fields to be selected ChildrenInlineFormset = inlineformset_factory( models.Parent, models.Child, form=ChildForm, formset=CustomFormset, min_num=1, max_num=50, extra=0, can_delete=True ) VIEW: @require_http_methods(["GET", "POST"]) def parent_update_view(request, pk): if request.method == "POST": parent = get_object_or_404(models.Parent, pk=pk) parent_form = forms.ParentForm(request.POST, instance=parent) child_item_formset = forms.ChildInlineFormset( request.POST, instance=parent ) if parent_form.is_valid() and child_item_formset.is_valid(): with transaction.atomic(): parent_form.save() child_item_formset.save() return redirect(reverse("parent_detail", … -
How to handle sorting, filtering and pagination in the same ListView
GitHub link: https://github.com/IgorArnaut/Django-ListView-Pagination-Search-Sorting-Issue I have an issue with the ListView. I have pagination, side form for filtering and a form with select for sorting in a single view. These 3 use get method and are "handled" in this list view. class ListingListView(generic.ListView): model = Listing context_object_name = "listings" template_name = "listings/listing_list.html" def get_context_data(self, **kwargs): context = super(ListingListView, self).get_context_data(**kwargs) context["form"] = SearchForm() return context def get_queryset(self): queryset = super(ListingListView, self).get_queryset() if (self.request.GET.dict()): query = filter(self.request.GET.dict()) queryset = queryset.filter(query) sorting = self.request.GET.get("sorting") if sorting == "new": queryset = queryset.order_by("-created_at") if sorting == "big": queryset = queryset.order_by("-apartment__area") if sorting == "small": queryset = queryset.order_by("apartment__area") if sorting == "expensive": queryset = queryset.order_by("-apartment__price") if sorting == "cheap": queryset = queryset.order_by("apartment__price") paginator = Paginator(queryset, per_page=2) page_number = self.request.GET.get("page") listings = paginator.get_page(page_number) return listings Urls: urlpatterns = [ path("", views.ListingListView.as_view(), name="listing-list"), path("postavka", login_required(views.ListingCreateView.as_view()), name="listing-create"), path("<int:pk>", views.ListingDetailView.as_view(), name="listing-detail"), path("<int:pk>/izmena", views.ListingUpdateView.as_view(), name="listing-update"), path("<int:pk>/brisanje", login_required(views.listing_delete), name="listing-delete") ] Templates: <div class="col-4">{% include "../partials/listings/search_form.html" %}</div> <div class="col-6"> <form class="mb-3" action="{% url 'listing-list' %}" method="get"> <select class="form-select w-50" name="sorting"> <option value="new">Prvo najnoviji</option> <option value="popular">Prvo najpopularniji</option> <option value="big">Po kvadraturi (opadajuće)</option> <option value="small">Po kvadraturi (rastuće)</option> <option value="expensive">Po ceni (opadajuće)</option> <option value="cheap">Po ceni (rastuće)</option> </select> </form> {% if listings %} {% for listing in listings %} … -
want a UI for archived user and therapists , [closed]
I have two models in my Django project: User and Therapist. Both have long lists of records in the database. Each model includes an archived_at field (a DateTimeField) that I use to mark when a user or therapist has been archived. I've already added an admin action that allows me to archive users and therapists via the Django Admin interface by setting the archived_at timestamp. Now, I want to improve the admin UI by providing a clear separation between active and archived records. Ideally, I'd like to have a dropdown or filter in the admin list view so that I can easily view: Only active users or therapists (archived_at is NULL) Only archived users or therapists (archived_at is not NULL) Or view all records (no filter applied) What’s the cleanest way to implement this kind of filter in Django Admin? Any help or code examples would be appreciated. -
Background daemon in celery without task explosions
I'm always having a hassle trying to have celery jobs scan the database for work, but to not have things done twice or submission explosions. The issue resides in that: periodic celery-beat jobs just keep submitting, even if there already are many added to the queue, and there's no way to cap this. E.g. have at most 1 of these in the queue or active. Unless you use celery inspect to test if a job already exists, but those calls can easily block for too long, I feel this particularly happens if workers are busy. This then can cause a ton of inspects being stacked up. This can cause job explosions, e.g. when beat keeps submitting but the worker is busy or down for a while, and once it comes up again, it a gazillion of them push through. What I'm looking for is a daemon-like process or thread that simply checks for things from the database that need processing, and that will wait if none are there (or query ever 30' or something like that). In this case, if the workload is too high, it doesn't particularly make sense to schedule the same thing a gazillion times. Keeping track … -
Can pyHanko digitally sign HTML content directly, or is PDF conversion required?
I’m working on a Django web application where documents are generated and displayed using styled HTML templates (e.g., for formal printable forms). These are rendered in the browser with proper formatting and layout. I am using pyHanko (version 0.29.0) to apply digital signatures via .p12 certificates, and it works great when signing pre-generated PDF files. However, in my case: The documents are originally in HTML format and rendered in the browser. I want to apply a digital signature directly to the document without converting to PDF first, if possible. Right now, I convert the HTML to PDF using tools like wkhtmltopdf or pdfkit, then pass the PDF to pyHanko for signing. This adds some complexity and dependency issues (e.g., rendering differences or install problems with wkhtmltopdf). Is there any way to digitally sign HTML-rendered documents directly using pyHanko, or is conversion to PDF strictly necessary? If PDF is required, are there any modern or reliable ways to convert HTML to PDF (ideally Python-based) that work smoothly with pyHanko? -
Why am I getting NoReverseMatch Error - Django
I'm having a reverse error in Django when visiting another URL "comment_post_view" The error is coming from when I visit the comment_post_view page; I'm thinking maybe it's because of the username in url, but I don't know how to go on with it. How can I get it done? URL path('p/<username>/status/<post_id>/', comment_post_view, name='comment_post_view'), path('settings/archive-post/', archive_post_view, name='archive_post_view'), path('archive-post/<id>/', archive_view, name='archive_view'), VIEWS.PY @login_required def comment_post_view(request, username, post_id): page_title = "Post Comment" username_url = get_object_or_404(User, username=username) user_post = get_object_or_404(Post, pk=post_id, poster_profile=username_url) # All users following posts user_profile = request.user.profile posts = Post.objects.filter( Q(id=user_post.id) ).order_by("?").select_related('poster_profile', 'poster_profile__profile').distinct() post_data = [] for post in posts: poster_profile = post.poster_profile.profile mutual_followers_qs = user_profile.following.filter( id__in=poster_profile.following.values_list('id', flat=True) ) post_data.append({ 'post': post, 'mutual_followers': mutual_followers_qs[:3], # You can select any number of followers here 'mutual_count': mutual_followers_qs[2:].count() }) ............................ @login_required def archive_post_view(request): page_title = "Archive Post" posts = Post.objects.filter( Q(is_hide=request.user) ).select_related('poster_profile', 'poster_profile__profile').distinct() post_data = [] for post in posts: poster_profile = post.poster_profile.profile post_data.append({ 'post': post, }) .......................... @login_required def archive_view(request, id): post = get_object_or_404(Post, id=id) if post.is_hide.filter(id=request.user.id).exists(): post.is_hide.remove(request.user) else: post.is_hide.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) TEMPLATE archive_post_view.html {% for item in post_data %} {% if request.user == item.post.poster_profile %} <a href="{% url 'site:archive_view' item.post.id %}">Archive post</a> # Current user {% else %} # Error pointing to … -
How to Safely Upgrade a Package in Django (e.g., django-jalali from 1.0.2 to 2.0.0) Without Breaking Existing Code?
I'm currently working on upgrading an older Django project and I have both a specific and a general question about package upgrades. 🔍 Specific Question: I’m using django-jalali-date==1.0.2 in one of my older projects, and I'd like to upgrade it to 2.0.0 because of some important improvements and features. But before I do that, I want to be sure this won't break anything — especially in forms, models, templates, or static files ({{ form.media }}, template filters like |to_jalali, etc.). So, how can I safely compare the two versions, test compatibility, and ensure everything keeps working as expected? Are there any known breaking changes between these versions? How can I verify if imports like JalaliDateField, AdminJalaliDateWidget, or template tags still work? Any advice on testing or migration steps would be great! 🔁 General Question: More broadly, what’s the best way to safely upgrade any Python/Django package without risking regressions? What strategies do you use when upgrading major versions (e.g., from v1.x.x to v2.x.x)? For example: Do you manually check changelogs and diffs? Do you run tests or use tools like pipdeptree, pytest, or diff tools? Do you create a staging environment first? Any tips for checking backward compatibility (BC)? I’d … -
Issue with Modelform
This is what I got after coding my ModelForm What could have caused that, I kept trying to debug it, but everything seems right, didn’t know where the errors are coming from This was the error I got after running the server, the first form worked out, as I was trying to redirect to another form, this error threw up raise ValueError ("ModelForm has no model class specified.") ValueError: ModelForm has no model class specified. I want it to work, I’m actually trying to build a web marketplace with Django, the only issue I go was the modelForm error and it really makes me worried -
Django cannot create record with correct foreign key to CharField with spaces in middle - getting surrounded by single and double quotes like "'a a'"
First of all - I understand that CharField is rather bad primary key, but it's unique in-game name, good 2 use as-is in many places, and may contain spacees. And IMHO the problem will repeat with non pkey field anyway 3 models - source, and two references. The first reference works perfectly in admin UI with the same code, the second - unworkanle during creating record class PilotUsers(AbstractUser, PermissionsMixin): first_name = None last_name = None username = None ed_name = models.CharField(primary_key=True,max_length=60,null=False,blank=False,unique=True,verbose_name='Pilot name in Elite Dangerous', ) squadron_tag = models.ForeignKey('Squadrons', verbose_name='Frontier squadron tag', on_delete=models.PROTECT, default='----') email = models.EmailField(unique=True) USERNAME_FIELD = 'ed_name' REQUIRED_FIELDS = ['email'] objects = PilotUserManager() def __str__(self): return self.ed_name class Meta: app_label = 'common_pages' This is working in admin UI - image below class Cert(DetailsModel, AbstractCert): organizational_unit_name = models.ForeignKey('common_pages.PilotUsers', verbose_name='ED Pilot Name', on_delete=models.PROTECT) class Meta(AbstractCert.Meta): abstract = False swappable = swapper.swappable_setting("posts", "Cert") This class ActionFeed(models.Model): pkey = models.BigAutoField(primary_key=True) received = models.DateTimeField(verbose_name='Date-time') ed_name = models.ForeignKey('common_pages.PilotUsers', verbose_name='ED Pilot Name', on_delete=models.CASCADE) #skipped raw_data = models.JSONField(verbose_name='Raw Data', null=False) is unworkable during creating new record print (f'Pilot = {pilot}') record = ActionFeed(received= ts, ed_name=pilot, #skipped raw_data = entry) The error is Cannot assign "'Al L****]'": "ActionFeed.ed_name" must be a "PilotUsers" instance. Attn - Single … -
Why is `djlint` warning me to add `<meta>` tags even though the file is linted?
I'm working on a Django web project and using djlint to lint and format my HTML templates. I ran the following command to lint one of my templates: djlint html_files/analytics/reports/report_new.html And I got this output: Linting 1/1 files ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 00:00 html_files/analytics/reports/report_new.html ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── H030 3:0 Consider adding a meta description. <html lang="{{ lang H031 3:0 Consider adding meta keywords. <html lang="{{ lang Linted 1 file, found 2 errors. Even though it says "found 2 errors", the file is actually linted and formatted just fine. There’s no crash, and the formatting is applied. What I want to understand: Why are these tagged as errors, when they’re really just recommendations? Should these be treated as warnings or ignored? Is it best practice to always include <meta name="description"> and <meta name="keywords"> in Django templates — even for internal dashboards? How can I suppress or ignore these suggestions if I don’t want to include them? Let me know if there's a way to configure djlint to stop flagging these without affecting actual linting or formatting. What I’ve tried: I checked the official djlint documentation, and these are listed under SEO-related suggestions. I also tried this command and it worked to silence the warnings: djlint html_files/analytics/reports/report_new.html … -
Web application creating
I am making my own web application which includes many functionalities similar to instagram. Can I build it by just Django framework can someone suggest me what tools or what else I must learn or use . -
psycopg2.errors.UndefinedTable: relation "committees_setting" does not exist
Error: ProgrammingError at /admin/committees/setting/ relation "committees_setting" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "committees_setting" ^ Request Method: GET Request URL: http://localhost:8000/admin/committees/setting/ Django Version: 4.0.8 Exception Type: ProgrammingError Exception Value: relation "committees_setting" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "committees_setting" ^ Exception Location: /usr/local/lib/python3.8/site-packages/django/db/backends/utils.py, line 89, in _execute Python Executable: /usr/local/bin/python Python Version: 3.8.17 Python Path: ['/app', '/app', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages', '/app/administration', '/app/administration'] My models: Settings: """Settings Committees models""" # Django from django.db import models # Models from administration.utils.models import BaseModel # Exceptions from administration.committees.exceptions import ( SettingsImproperlyConfigured, ) class Setting(BaseModel): """ Settings Committees model A Settings Committees Model contains business information about the committee. """ committee = models.OneToOneField( "committees.Committee", on_delete=models.CASCADE, related_name="settings" ) settings = models.JSONField() def __str__(self): """Return committee name""" return f"{self.committee}' settings" def get_setting(self, key, default=False): """Return dynamic key setting""" return self.settings.get(key, default) def late_fee_settings(self): """Return late fee setting""" late_fee_settings = self.settings.get("late_fee", False) if not late_fee_settings: raise SettingsImproperlyConfigured("late_fee not fount") return late_fee_settings def late_fee_is_active(self): """Return late fee setting""" late_fee_settings = self.late_fee_settings() return late_fee_settings.get("active", False) def late_fee_percentage(self): """Return late fee setting""" late_fee_settings = self.late_fee_settings() late_fee_percentage = late_fee_settings.get("percentage", False) if not late_fee_percentage: raise SettingsImproperlyConfigured("late fee percentage not fount") return late_fee_percentage def late_fee_has_penalty_fee(self): """Return late … -
How to correctly add a custom '--dry-run' argument to a Django Extensions `runjob` command?
I have a custom Django management job created using django_extensions that deletes old database records. To avoid unintended deletions, I want to add a --dry-run argument to simulate deletions without actually removing data. However, when I execute the command with: uv run python manage.py runjob delete_recordings --dry-run I receive this error: manage.py runjob: error: unrecognized arguments: --dry-run Here's how my simplified job class currently looks: from django_extensions.management.jobs import HourlyJob import logging logger = logging.getLogger(__name__) class Job(HourlyJob): @classmethod def add_arguments(cls, parser): parser.add_argument( '--dry-run', action='store_true', help='Execute the job in simulation mode without deleting any data.', default=False, ) def execute(self, *args, **options): dry_run = options.get('dry-run', False) if dry_run: logger.info("Executing in DRY-RUN mode.") # Logic here to delete records or simulate deletion based on dry_run I followed the Django Extensions documentation to add a custom argument (--dry-run). I expected that when running the command with --dry-run, it would recognize the argument and simulate the operation, logging the intended deletions without performing them. However, the command line returns an error indicating that the argument is not recognized. It seems that Django Extensions isn't picking up the custom argument defined in my job class. What is the correct way to add a custom argument (--dry-run) to … -
assign a custom field order_sl
I'm working with a Django model where I need to assign a custom field order_sl that should increment from the last existing value with a specific filter. Here's what I'm doing currently: prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() But I believe this approach is problematic: It pulls the last value into Python instead of handling it in the DB. It’s not thread-safe and likely to break under race conditions if multiple inserts happen at the same time. I'm using PostgreSQL, and I want to ensure that each new row gets a unique, sequential order_sl based on the highest existing value or a dedicated sequence. The order_sl field is not the primary key, and I don’t want to make it an AutoField. ❓ What’s the best, Django-safe, PostgreSQL-optimized way to handle this? Would a raw SQL sequence be better? Or should I use select_for_update() with a transaction block? Thanks! -
Understanding F expression in Django
What I have done is - prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() return But I'm not sure about this, this is loading the previous value into the python and not directly managing the database (i think so), as it should be in the case of F expression and it may fail race condition. Can you let me know the correct way, I have to increase the value by 1 (from the last row) in the new row. Thanks -
Django DisallowedHost Error Despite Domain Being in ALLOWED_HOSTS
Problem Description I'm getting a DisallowedHost error in my Django production environment, even though the domain is clearly listed in my ALLOWED_HOSTS setting. I am using traefik. Error Message: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'api.tuitionwave.com'. You may need to add 'api.tuitionwave.com' to ALLOWED_HOSTS. Current Configuration: My production.py settings file includes: ALLOWED_HOSTS configuration ALLOWED_HOSTS = ["api.tuitionwave.com", "localhost", "127.0.0.1", "django"] # Trust proxy headers USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True # Security settings SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) What I've Tried Verified that api.tuitionwave.com is explicitly listed in ALLOWED_HOSTS List item Confirmed the settings file is being loaded correctly Checked that there are no whitespace issues in the domain name And here is my traefik.yml File details http: routers: web-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web middlewares: - redirect service: django web-secure-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web-secure middlewares: - default-headers service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt -
How to intercept a form submit in websocket connection?
I have "inherited" a piece of code from a chat application. I would like to add some custom checks on the user input upon submission, allowing the submit to be aborted on client side if necessary. I have created a submit handler javascript function in order to execute the checks and transformations, including preventDefault as first instruction: async handleSubmit(event) { event.preventDefault(); // Prevent default form submission ... I have linked the handler to the form: <form class="pg-chat-input-bar" ws-send @submit="handleSubmit($event)" enctype="multipart/form-data" > Yet, no matter what, the form is submitted immediately when the submit button is pressed. The server receives the form in parallel to / before the handler being executed. I can assess that the handler is triggered and does what it is supposed to do but unfortunately the form has already been submitted. I tried @submit.prevent, @submit.stop and even combined both but it doesn't change the outcome. I found many posts asking to capture/intercept/interrupt a form submit but the solutions are as simple as what I tried. What am I doing wrong? As I am not starting from scratch I would prefer modify the code as little as possible and use what is already there. Could it be related … -
How to compare a DecimalField value in Django templates for conditional logic?
I'm working on a Django project where users have an Account model with a DecimalField named account_balance. I'm trying to conditionally show a KYC verification link if the user's balance is exactly 100, and show an error if it's less than that. Here’s my setup: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_balance = models.DecimalField(max_digits=10, decimal_places=2) class KYC(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField() views.py: def settings(request): kycs = KYC.objects.filter(user=request.user) context = { "kycs": kycs, } return render(request, 'public_pages/settings.html', context) template: {% for kyc in kycs %} <p>Your identity is important to the community</p> {% if kyc.user.account.account_balance == 100 %} <a href="{% url 'Kyc_Form' kyc.slug %}">Update KYC</a> {% elif kyc.user.account.account_balance < 100 %} <div class="alert alert-danger"> You need at least 100 coins before applying for KYC. </div> {% endif %} {% endfor %} But this block never renders either the button or the error message. The only thing I see is the static text: <p>Your identity is important to the community</p> I tried printing the balance outside the logic: <p>Balance: {{ kyc.user.account.account_balance }}</p> And it shows something like 100.00. I assume it's a Decimal issue. How can I properly compare a DecimalField like account_balance in the Django template to check … -
Will requests to my site lag and work slowly in django while waiting for celery results?
I use django to create pdf to docx converter using pdf2docx library, and I need to wait a celery task to done and get result from it. Will my site lag and work slowly if a lot of users use it, and how can i do it better? here my views and celery code views.py ''' from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.http.request import HttpRequest import tempfile import os from .forms import FileUploadForm from django.views.decorators.csrf import csrf_protect from . import tasks from celery.result import AsyncResult @csrf_protect def main_page(request: HttpRequest): if request.method == "GET": # get form = FileUploadForm(request.POST, request.FILES) context = { "form": form } return render(request, 'main/main_page.html', context) if request.method == 'POST' and request.FILES.get('file'): form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): # get file file = request.FILES['file'] size_limit = 2 * 1024 * 1024 # save pdf with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file: if file.size > size_limit: for chunk in file.chunks(): temp_file.write(chunk) else: temp_file.write(file.read()) temp_pdf_path = temp_file.name # start convertor task task: AsyncResult = tasks.convert_pdf_to_docx.delay(temp_pdf_path) # get docx path temp_docx_path = task.wait(timeout=None, interval=0.5) converted_file_name = str(file).replace(".pdf", "") # read docx file and set it in response with open(temp_docx_path, 'rb') as docx_file: file_data = docx_file.read() response = HttpResponse(file_data, … -
django-celery-results: error ModuleNotFoundError: No module named 'django_celery_results'
I try to run "celery -A myproj worker -l info" and it gives me the error ModuleNotFoundError: No module named 'django_celery_results'. All dependencies are installed (django, celery, django-celery-results, redis). I tried to run it with admin rights, but it didn't help as well. I tried changing the python version from 3.13 to 3.11, but also without result. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_results',] -
How to store the refresh token in HttpOnly cookie with Google OAuth2 (PKCE flow) in Django?
I'm using Django with drf_social_oauth2 and oauth2_provider for Google OAuth2 authentication. I’ve successfully implemented the PKCE authorization flow. Step 1: Frontend redirects to: GET /api/v1/o/authorize/?client_id=<client_id>&response_type=code&redirect_uri=http://127.0.0.1:5173/callback&code_challenge=<challenge>&code_challenge_method=S256 Step 2: Frontend exchanges code at: POST /api/v1/o/token/. Backend responds with: { "access_token": "...", "expires_in": 36000, "refresh_token": "...", ← this is what I want to move into a cookie ... } My configuration: # urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/o/", include("oauth2_provider.urls", namespace="oauth2_provider")), ] # settings.py (snippets) INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'drf_social_oauth2.backends.DjangoOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<your-client-id>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<your-client-secret>' REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } LOGIN_REDIRECT_URL = "/" What works: PKCE is working. Google OAuth2 authorization is integrated using social-auth-app-django and drf-social-oauth2. I can extract the original Google access_token from the user's social_auth.extra_data. What I want: I want to store the refresh_token in a secure HttpOnly cookie instead of returning it in the JSON response — to reduce XSS risks. I would be grateful for any advice, code examples on how to solve this, or references to sources where a solution can be found.