Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery with prefork workers breaks OpenTelemetry metrics
I have a Django application I wanted to instrument with OpenTelemetry for traces and metrics. I created an otel_config.py file next to my manage.py with this content: # resources def get_default_service_instance_id(): try: hostname = socket.gethostname() or "unknown-host" except Exception as e: hostname = "unknown-host" try: process_id = os.getpid() except Exception as e: process_id = "unknown-pid" return f"{hostname}-{process_id}" service_name = "my-service" otlp_endpoint = "http://otel-collector:4318" service_instance_id = get_default_service_instance_id() resource = Resource.create( { SERVICE_NAME: service_name, SERVICE_INSTANCE_ID: service_instance_id, } ) # traces otlp_endpoint_traces = urljoin(otlp_endpoint, "/v1/traces") trace_exporter = OTLPSpanExporter(endpoint=otlp_endpoint_traces) span_processor = BatchSpanProcessor(trace_exporter) tracer_provider = TracerProvider(resource=resource) trace.set_tracer_provider(tracer_provider) trace.get_tracer_provider().add_span_processor(span_processor) # metrics otlp_endpoint_metrics = urljoin(otlp_endpoint, "/v1/metrics") metric_exporter = OTLPMetricExporter(endpoint=otlp_endpoint_metrics) metric_reader = PeriodicExportingMetricReader(metric_exporter) meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader]) metrics.set_meter_provider(meter_provider) # instrument DjangoInstrumentor().instrument() Psycopg2Instrumentor().instrument() CeleryInstrumentor().instrument() Then, I simply imported it at the end of my settings.py file like below: import otel_config Although my traces and metrics work fine in most cases, my OpenTelemetry metrics are broken in the case of celery workers with prefork mode. In case of prefork workers, the child processes happen to get the same SERVICE_INSTANCE_ID as the parent process. Therefore, different child processes manipulate the same metric value as each has its own exclusive memory. Thus, the value in my collector gets changed very often and … -
moving from Django-WSGI to ASGI/Uvicorn: issue with AppConfig.ready() being called synchronously in asynchronous context
I'm moving my application views to asynchronous calls as they are requesting a number of data from the database. When running the async views from the wsgi server, everything is working according to expectations. But to be able to really benefit from the async rewriting of my application, I'm now trying to start my application as a asgi application, together with Uvicorn. asgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyAppName.settings') application = get_asgi_application() While launching the asgi server through: uvicorn MyAppName.asgi:application I end up triggering: SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async The reason is that through my AppConfig.ready() method, I'm calling a function which populates some key data from database in cache. my_app/apps.py: class MyAppConfig(AppConfig): name = 'my_app' def ready(self): """ hook for application initialization : is called as soon as the registry is fully populated for this app put your startup code here useful to run some code inside the Django appserver process or you need to initialize something in memory, in the context of the Django app server """ # Reinitializing cache to enable the cached_dicts to get the right values: cached_dicts.set_up_cache_dicts() AppConfig.ready() is by design a sync method in Django, but the … -
Django message not showing up in template
I’m using Django 5.2.4, and my login_user view sets an error message with messages.error when authentication fails, but it doesn’t appear in the template (login page) after redirecting. App urls: from django.urls import path from django.shortcuts import redirect from . import views # urlpatterns of the app checks the function names defined in views urlpatterns = [ path('', lambda request: redirect('login', permanent=True)), path("login/", views.login_user, name="login"), ] Project urls: from django.contrib import admin from django.shortcuts import redirect from django.urls import path, include urlpatterns = [ path("", lambda request: redirect('loginapp/', permanent=True)), path('admin/', admin.site.urls), path("loginapp/", include("loginapp.urls")), path("loginapp/", include('django.contrib.auth.urls')), ] template html : <html lang="en"> <body> <div class="box"> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <h2>Welcome to Trevo</h2> <h3>Sign in now!</h3> <form method="post", action="{% url 'login' %}"> <!-- Django uses to verify that the form submission is coming from your site and not from a malicious third party. --> {% csrf_token %} <label for="Username">Username</label><br> <input type="text" id="username" name="username"><br> <br> <label for="Password">Password</label><br> <input type="password" id="password" name="password"><br> <br> <input type="submit" id="submit" name="submit" value="Sign in"><br> </form> </div> <style> Views.py : from django.shortcuts import render, … -
How to show in django template data from connected models?
I have a models: class Publication(models.Model): pub_text = models.TextField(null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) pub_author = models.ForeignKey(User, on_delete=models.CASCADE) coor_text = models.CharField(null=True, blank=True) coor_adress = models.CharField(null=True, blank=True) coor_coordinates = models.CharField(null=True, blank=True) class Image(models.Model): image = models.ImageField(upload_to='images', null=True) image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, related_name='images') And i have view: def pub_list_view(request): pubs = Publication.objects.all() images = Image.objects.all() context = {"pubs": pubs, "images": images} return render(request, "epictalk/pub_list.html", context) And i have template: {% extends 'epictalk/layout.html' %} {% block content %} {% for pub in pubs %} <h1>{{ pub.pub_text }}</h1> {% for image in images %} <img src="{{ image.image.url }}"> {% endfor %} {% endfor %} {% endblock %} How to show in browser a Publications with a connected images to it? How to show in browser a Publications with a connected frist image to it? -
django-import-export id auto generated by the package during insert?
I'm using django-import-export and trying to work it with multi-thread concurrency. I tried logging the sql queries and notice that INSERT query has id values generated as well. INSERT INTO "lprovider" ("id", "npi", "provider_id", "first_name", "last_name") VALUES (278082, '1345', NULL, 'CHARLES', 'STEVENS') Is it expected? The package self populates the primary key? -
Postgres indexing fails in Django
Tried to set db_index=True, HashIndex and BrinIndex, nothing works, indexes by Seq Scan, there are 1000 records in the database, all migrations are completed. Model code: from django.db import models from django.utils import timezone from django.contrib.postgres.indexes import BrinIndex, HashIndex class Contact(models.Model): phone = models.CharField(max_length=50, unique=True) address = models.CharField(max_length=50) def __str__(self): return self.phone class Department(models.Model): name = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) about = models.CharField(max_length=10000,db_index=True) age = models.SmallIntegerField(null=True) created = models.DateTimeField(default=timezone.now) work_experience = models.SmallIntegerField(default=0, null=True) contact = models.OneToOneField(Contact, on_delete=models.CASCADE, null=True) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=None, null=True) class Meta: indexes = ( BrinIndex(fields=('created',), name="hr_employee_created_ix", pages_per_range=2 ), ) def __str__(self): return f'{self.first_name} {self.last_name}' I tried this filters: employees = Employee.objects.filter(created__year__lte=2022) employees = Employee.objects.filter(about__contains='Test') -
Bad Request /api/accounts/register/ HTTP/1.1" 400 50
I am a newbie to ReactJS and Django REST Framework. I am trying to connect the frontend registration form to a backend API to no avail; I keep getting "POST /api/accounts/register/ HTTP/1.1" 400 50' error. The following are codes: endpoints: from django.urls import path from .views import RegisterView, LoginView, AuditLogView urlpatterns = [ path('admin/', admin.site.urls), path('api/accounts/', include('accounts.urls')), ] App URLs: urlpatterns = [ path('register/', RegisterView.as_view(), name='register'), path('login/', LoginView.as_view(), name='login'), path('audit-logs/', AuditLogView.as_view(), name='audit-logs'), ] On the part of ReactJS, frontend, I provide a connection to the backend using axios as follows: import axios from "axios"; const API = axios.create({ baseURL: "http://localhost:8000/api/accounts/", // Change this to match your Django backend }); // Register a new user export const registerUser = (userData) => API.post("register/", userData); // Login and receive token export const loginUser = (credentials) => API.post("login/", credentials); // Get audit logs (SUPERUSER only) export const getAuditLogs = (token) => API.get("audit-logs/", { headers: { Authorization: `Token ${token}` }, }); // Get user profile (optional if endpoint exists on your backend) export const getUserProfile = (token) => API.get("profile/", { headers: { Authorization: `Token ${token}` }, }); // Logout (optional if you implement token blacklist on server) export const logoutUser = (token) => API.post( "logout/", … -
Why are some folders and files still red in PyCharm even though the Django project works correctly?
I'm working on a Django project in PyCharm, and although everything works fine (including migrations, interpreter setup, Django installation, and manage.py is in the correct place), some folders and .py files like models.py, admin.py, etc., still appear in red in the Project view. Marked the correct root folder (the one containing manage.py) as Sources Root Ensured all packages (blog, djangoProject) have init.py All imports are correct and not showing any actual errors Ran Invalidate Caches / Restart -
Email verification in django python
I try to make email verification in django, everyting works correctly, but if user creates account with someone other's email and if user will not confirm email, owner of this email will not be able to register because account is alredy registered and is_active is False. Here my views.py with reg form ''' from django.shortcuts import render, redirect from django.http.request import HttpRequest from django.http import JsonResponse from .forms import UserRegisterForm, UserLoginForm from .models import User from .tokens import accound_activate_token from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.utils.encoding import force_bytes, force_str from django.core.mail import send_mail # from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login, logout def send_email_validation(request: HttpRequest, user: User, form: UserRegisterForm): current_site = get_current_site(request) mail_subject = "Activate your account" message = render_to_string( "users/emails/email_activation.html", { "user": user, "domain": current_site.domain, "uid": urlsafe_base64_encode(force_bytes(user.pk)), 'token': accound_activate_token.make_token(user) } ) from_email = "xxx" to_email = form.cleaned_data["email"] send_mail( mail_subject, message, from_email, [to_email] ) def register_page(request: HttpRequest): if request.method == "GET": reg_form = UserRegisterForm() if request.method == "POST": reg_form = UserRegisterForm(request.POST) # create user and redirect to login if reg_form.is_valid(): user: User = reg_form.save(commit=False) user.is_active = False user.save() # sending email for validation send_email_validation(request, user, reg_form) return redirect("users_login") context = … -
activate script missing from Python virtual environment (venv) on Ubuntu 22.04 with Python 3.12
I'm trying to deploy a Django project on my Ubuntu server using a virtual environment. I created a directory named ae9f7a37e98d4a8f98643ced843d71d7_venv, but when I try to activate it using: source /www/wwwroot/ayale_atv/ae9f7a37e98d4a8f98643ced843d71d7_venv/bin/activate I get this error: -bash: /www/wwwroot/ayale_atv/ae9f7a37e98d4a8f98643ced843d71d7_venv/bin/activate: No such file or directory When I check the contents of the bin/ folder, I see Python binaries but no activate script: ls -l /www/wwwroot/ayale_atv/ae9f7a37e98d4a8f98643ced843d71d7_venv/bin Output: 2to3 pip3 pydoc3 python3.12 idle3 pip3.12 python3 python3.12-config It seems like the virtual environment wasn't set up correctly. I'm using Python 3.12.3 and Ubuntu 22.04. What caused this, and how can I properly create a working virtual environment so I can run my Django project? i use aapanel for deploy this Django app aapanel -
Django-tenants: relation "journal_nav_topnavitem" does not exist even after adding app to SHARED_APPS and running migrate_schemas --shared
I'm working on a multi-tenant Django project using django-tenants with Django 3.2.16. I created an app called journal_nav and initially added it only to TENANT_APPS. Later, I moved it to SHARED_APPS because it provides a common navigation bar for all tenants and the public schema. I added it to SHARED_APPS in settings.py: SHARED_APPS = [ 'app123', 'app456', ... 'journal_nav', # moved here ] However, when I visited a route that used a template context processor that queried TopNavItem.objects.all(), I got the following error: Internal Server Error: /services/typography/ django.db.utils.ProgrammingError: relation "journal_nav_topnavitem" does not exist LINE 1: ...", "journal_nav_topnavitem"."show_in_topbar" FROM "journal_n... I then ran: python manage.py migrate_schemas --shared But it showed: [standard:public] Running migrations: No migrations to apply. Even though the model clearly existed and the migration file (0001_initial.py) was present. -
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 …