Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a Django ListView with FormMixin?
I have a working ListView with template. I want to filter the list based on the contents of a form, something like: class SampleListView(FormMixin, ListView): model = Sample paginate_by = 15 form_class = LookupForm def get_queryset(self): samples = Sample.objects.all() # filter based on validated form contents form = self.get_form() if form.is_valid(): samples = samples.filter(some_property__gte=form.cleaned_data['sample_number']) return samples class LookupForm(forms.Form): sample_number = IntegerField(widget=NumberInput) The template shows the form as: <form action="" method='get'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Query samples'> </form> This renders the page with my list and form, but the form always seems to be invalid. How can I integrate the validated form with my ListView? Is this the Avoid anything more complex? That is, should I just not be trying to put the FormMixin and ListView together? -
For files uploaded via Django, how can I use them with libraries that require a hard file path to the file?
I am currently working on a text extraction component of my Django backend, which intends to extract text from urls (working), pure text (working), and files (.pdf, .doc, .ppt, .md, .txt, .html). My current code works for hardcoded file paths to valid file inputs: def extract_from_file(uploaded_file): file_type = os.path.splitext(uploaded_file.name)[1].lower() if file_type == ".pdf": text = pdf_to_text(uploaded_file) elif file_type in [".doc", ".docx", ".docm", ".dot", ".dotx", ".dotm"]: text = doc_to_text(uploaded_file) elif file_type in [".ppt", ".pptx", ".pps", ".ppsx"]: text = ppt_to_text(uploaded_file) elif file_type in [".md", ".html", ".htm"]: text = html_to_text(uploaded_file, file_type) elif file_type == ".txt": # adapted from https://www.geeksforgeeks.org/pandas/read-html-file-in-python-using-pandas/ with open(uploaded_file, "r", encoding="utf-8") as f: text = f.read() else: raise ValueError("Unsupported file type: " + file_type) if text: return article_from_text(text) else: raise ValueError("No text could be extracted from the file.") def pdf_to_text(file): reader = PdfReader(file.file) return "".join([page.extract_text() for page in reader.pages]) def doc_to_text(file): document = Document() document.LoadFromFile(file) text = document.GetText() document.Close() return text def ppt_to_text(file): presentation = Presentation() presentation.LoadFromFile(file) sb = [] # Loop through all slides and extract test to sb list - O(n^3) - maybe better way to do later? - quite slow # based on https://github.com/eiceblue/Spire.Presentation-for-Python/blob/main/Python%20Examples/02_ParagraphAndText/ExtractText.py for slide in presentation.Slides: for shape in slide.Shapes: if isinstance(shape, IAutoShape): for tp in … -
Should a single API call handle everything to make life of frontend easy, or there be as many apis as needed [closed]
So I face this issue often. Apart from being a backend python dev, I also have to handle a team consisting of frontend guys as well. We are into SPAs, and a single page of ours sometime contain a lot of information. My APIs also control the UI on the frontend part. For example, a single could contain. Order Detail Buttons that will be displayed based on role. like a staff can only see the order, whereas a supervisor can modify it. And like this sometime there are even 10 of such buttons. Order metadata. Like a staff will only see the order date and quantity whereas manager can also see unit and sale cost. Also, let's say there is something like order_assigned_to, then in that case I will also send a list of eligible users to which order can be assigned. (In this particular case, i can also make one more API "get-eligible-users/<order_id>/". But which one is preferred. Somehow, my frontend guys don't like many APIs, I myself has not worked that much with next, react. So, I do what they ask me for. Generally what is preferred ? My APIs are very tightly coupled , do we take … -
Python as a backend developer [closed]
Hey developers i am currently working in small startup company as a backend developer using python language , i want some suggestions like backend devs on which things they have to focus more. -
django backend is good shoes to learn now?
I have some experience with Python, and I’m interested in backend development. Is Django still a good choice to learn in the current job market? I’m particularly interested in its relevance for modern web applications and career opportunities compared to other backend frameworks. -
DRF unable to find existing model item in API
I am creating an API with Django Rest Framework and I keep encoutering an issue where i am unable to pull a single item from my django model on the browser. I have two endpoints one that gets the consumer by id and the other that gets ll the consumers. The one that gets all the consumers works fine and I am able to load the onto the browser but when it comes to grabbing the a single item but id which is a UUID it seems to fail or more so it keeps hitting a 404. I have checked that the id exists in the DB and there are entries there Just to point out this is all dummy data Views.py @api_view(["GET"]) def get_power_consumer_by_id(request, power_consumer_id): power_consumer = get_object_or_404(PowerConsumer, id=power_consumer_id) serializer = PowerConsumerSerializer(power_consumer) return Response( serializer.data, status=status.HTTP_200_OK ) @api_view(["GET"]) def get_power_consumer(request): if request.method == "GET": try: power_consumer = PowerConsumer.objects.all() serializer = PowerConsumerSerializer(power_consumer, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception: return Response( {"error": "Failed to get power consumer data"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) Url Patterns urlpatterns = [ path("v1/power_consumer/<uuid:power_consumer_id>/", get_power_consumer_by_id), path("v1/power_consumer/", get_power_consumer) ] JSON Response [{"id":"bbbbbbb2-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0002","billing_mode":"MANUAL_INVOICE","billing_cycle":"MONTHLY","billing_day_of_month":20,"billing_time":"02:00:00","predicted_bill_kobo":1200000,"deficit_amount_kobo":0,"is_at_risk":false,"next_billing_at":"2026-02-20T02:00:00Z","last_billed_at":"2026-01-20T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb3-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0003","billing_mode":"AUTO_CHARGE","billing_cycle":"WEEKLY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":300000,"deficit_amount_kobo":50000,"is_at_risk":true,"next_billing_at":"2026-01-29T02:00:00Z","last_billed_at":"2026-01-22T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb4-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0004","billing_mode":"MANUAL_INVOICE","billing_cycle":"BIWEEKLY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":800000,"deficit_amount_kobo":150000,"is_at_risk":false,"next_billing_at":"2026-01-28T02:00:00Z","last_billed_at":"2026-01-14T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"},{"id":"bbbbbbb5-bbbb-bbbb-bbbb-bbbbbbbbbbbb","account_number":"PC-0005","billing_mode":"AUTO_CHARGE","billing_cycle":"DAILY","billing_day_of_month":null,"billing_time":"02:00:00","predicted_bill_kobo":45000,"deficit_amount_kobo":0,"is_at_risk":false,"next_billing_at":"2026-01-26T02:00:00Z","last_billed_at":"2026-01-25T02:00:00Z","supplier":"aaaaaaa1-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}] Model Code class PowerConsumer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) supplier = models.ForeignKey(PowerSupplier, on_delete=models.CASCADE) account_number = models.CharField(max_length=100, unique=True) billing_mode … -
Unsure if I can learn Django [closed]
I have just completed Python fundamentals recently covering lists, tuples, dictionaries, basic OOP etc. However, I'm not certain whether it's the right time for me to dive into Django. -
Django-axes seems to ignore ipware settings behind Nginx
I'm struggling to set up my django-axes behind Nginx reverse proxy to take the HTTP_X_FORWARDED_FOR instead REMOTE_ADDR. I've tried all three variations as outlined here: https://django-axes.readthedocs.io/en/latest/4_configuration.html. I've tried setting the ipware fields in isolation as well as in combinations. Left-most and right-most also didn't make any difference., ip_address from Axes' attempts was always populated with REMOTE_ADDR. I'm 100% sure that request.META contains both HTTP_X_FORWARDED_FOR as well as REMOTE_ADDR. I checked this by inserting a debugging middleware in front of axes. My logs show that both values are valid and I can manipulate the IP logged by Axes by modifying REMOTE_ADDR in my middleware: class OverwriteRemoteAddrMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): logger = logging.getLogger('django.request') xff = request.META.get('HTTP_X_FORWARDED_FOR') logger.info(f"[Middleware] Before: HTTP_X_FORWARDED_FOR={xff}, REMOTE_ADDR={request.META.get('REMOTE_ADDR')}") # Set REMOTE_ADDR to a fixed unrelated value for testing request.META['REMOTE_ADDR'] = None logger.info(f"[Middleware] After: REMOTE_ADDR={request.META['REMOTE_ADDR']}, X-Forwarded-For={xff}") return self.get_response(request) This is my full settings.py that I'm currently using in a minimal django test project: """ Django settings for django_test project. Generated by 'django-admin startproject' using Django 6.0.1. """ from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-a8_oxq6w3m()1fh)%)srfm!prh_#4tsp3(kc2+37_@krm_++$%' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'axes', 'app', ] … -
Django: exception in get_catalog()
I have a limited set of LANGUAGES: LANGUAGE_CODE='sl' # It's for locals first of all LANGUAGES=[ ('sl', _('Slovene')), # First is default ('en', _('English')), ('it', _('Italian')), ('de', _('German')), ('ru', _('Russian')), ] But not everything is translated, mainly they're to have additional fields for django_modeltranslation. I've added this line to see what's happening right after "while True" in django/views/i18n.py:get_catalog(): print(translation, translation._fallback) For en_US value in accept_language header, all is fine: <DjangoTranslation lang:en> <gettext.GNUTranslations object at 0x7f07f59cb070> <gettext.GNUTranslations object at 0x7f07f59cb070> <gettext.GNUTranslations object at 0x7f07f59cb0e0> <gettext.GNUTranslations object at 0x7f07f59cb0e0> None For sl_SI all is good as well: <DjangoTranslation lang:sl> None But for de_DE (or ru_RU) it crashes: <DjangoTranslation lang:de> <DjangoTranslation lang:sl> <DjangoTranslation lang:sl> <django_countries.EmptyFallbackTranslator object at 0x7f07f6ccbcb0> <django_countries.EmptyFallbackTranslator object at 0x7f07f6ccbcb0> None Internal Server Error: /jsi18n/ Traceback (most recent call last): File "/home/pooh/venv13/lib/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/pooh/venv13/lib/python3.13/site-packages/django/core/handlers/base.py", line 198, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/generic/base.py", line 106, in view return self.dispatch(request, *args, **kwargs) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/generic/base.py", line 145, in dispatch return handler(request, *args, **kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 124, in get context = self.get_context_data(**kwargs) File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 210, in get_context_data "catalog": self.get_catalog(), ~~~~~~~~~~~~~~~~^^ File "/home/pooh/venv13/lib/python3.13/site-packages/django/views/i18n.py", line 187, in get_catalog for key, value in translation._catalog.items(): ^^^^^^^^^^^^^^^^^^^^ … -
Why won't Django render its select widget with this code
I am trying to use Django's default select widget to render an html dropdown and I just can't seem to figure out what I am doing wrong... here is my models.py class VehicleYear(TimeStampedModel): oem_year = models.IntegerField( unique=True, null=False, blank=False, default=current_year, validators=[ MinValueValidator(1900), max_value_current_year]) here is my forms.py class SelectYear(forms.Form): vehicle_year = forms.ModelChoiceField(queryset=VehicleYear.objects.all(), label="Select Year") here is my views.py def Year(request): context = {'form': SelectYear()} return render(request, 'vehicles/select_year.html', context) here is my html template(select_year.html): {{ form.as_p }} select_year.html is part of select_filter.html and is using {% include "folder/select_year.html" %} -
How to migrate data for email field
So i have a char field which i was using to store emails. Now there are some rule/validation and processes for email fields like email validation and email normalization etc. I have to add the validation and email normalization on the field while keeping in CharField. what is the valid and safe ways to do this? I am using Django and DRF. -
Disable add, edit and delete views and widgets for a custom Wagtail ViewSet index page
I have this Django model: class Player(models.Model): class Meta: verbose_name = _("Player") verbose_name_plural = _("Players") first_name = models.CharField(verbose_name=_("First Name"), blank=False, null=False, max_length=255) last_name = models.CharField(verbose_name=_("Last Name"), blank=False, null=False, max_length=255) email = models.EmailField(verbose_name=_("Email"), blank=False, null=False, max_length=255) uid = models.UUIDField(unique=True, blank=False, null=False, editable=False) objects = PlayerManager() @property def name(self): return f"{self.first_name} {self.last_name}" # Add verbose name for custom property name.fget.short_description = _("Full Name") And this custom ViewSet to display it in the Wagtail Admin interface: class PlayerListViewSet(ModelViewSet): model = Player name = "players" add_to_settings_menu = False add_to_admin_menu = False list_display = ( "name", "email", "uid" ) search_fields = ("first_name", "last_name", "email",) # Disable Player CRUD create_view_enabled = False edit_view_enabled = False delete_view_enabled = False # Disable forms exclude_form_fields = "__all__" # Block CRUD permissions def has_add_permission(self, request): return False def has_edit_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def get_index_view_kwargs(self, **kwargs): kwargs = super().get_index_view_kwargs(**kwargs) kwargs["show_add_button"] = False return kwargs The problem is - I don't want the Player models to be created, edited or deleted via the admin interface - only a list view should be accessible. I added attributes above, but the edit/delete and add widgets are still displayed on the page. Is there a way to disable … -
django archive user if clicked for detail page view an error appears
so i have this user model and in admin.py which ofcourse is used by my client as admin page view and recently my client requested that the user/s who has been archived should not show in the active list page of in the django admin ,but can be viewed if filtered so i put the functionality in my base " get_queryset " which is as follow def get_queryset(self, request): qs = super().get_queryset(request) # detecting if archive date filter is applied archive_filter_applied = any( key.startswith("archived_at__") for key in request.GET ) # default behaviour which excludes archived users if not archive_filter_applied: qs = qs.filter(archived_at__isnull=True) if request.user.is_superuser: return qs # permission gate if not request.user.has_perm("api.view_user"): return qs.none() therapist_qs = qs.filter( Q(treatment_therapist=request.user) | Q(assessment_therapist=request.user) ) # data-driven therapist rule if therapist_qs.exists(): return therapist_qs return qs so what happens is as normal the users are shown who are active and not archived but if filter through a filter only those are shown which are archived so till here all is fine but when the archived user is clicked in the list page to see his details page an error appears like this " Client with ID “375” doesn’t exist. Perhaps it was deleted?" i have … -
How can I set up a new string for comments in PyCharm for DTL code in .html file?
In PyCharm we have a convinient way to turn off for a while a part of code by pressing Ctrl+/. Later we can turn it on by pressing the same key combination. However if I am in HTML page the combination Ctrl+/ generates comments <!--some error here-->. It works well in HTML code. But if use DTL (Dynamic Template Language) from Django the comments should be as follows: {% some error code here %}. Is there any way to set up the key combination Ctrl+/ in PyCharm for making the DTL comments i.e. {% some error code here %}? I use PyCharm 2023.1.2 (Community Edition) and Django 5.2.10. -
Designing a flexible relationships model in Django
I'm designing a small Django app, and writing some code snippets to go with the design. I have some simple models in the design, like Person and Book: from django.db import models class Book(models.Model): name = models.CharField(max_length=127) class Person(models.Model): name = models.CharField(max_length=127) I want to be able to express multiple types of relationships between multiple models in the application, as the application grows. In the example above, there are multiple possible types of relationships, for example: a Person is the author of a Book a Person is the editor of a Book a Person is the subject of a Book (e.g. if the book is a biography) a Person is both the author and the subject of a book (e.g. if the book is an autobiography) So I'm thinking of a model that expresses relationship types, like this: from django.contrib.contenttypes.models import ContentType class RelationshipType(models.Model): model_a = models.ForeignKey(ContentType, on_delete=models.PROTECT) model_b = models.ForeignKey(ContentType, on_delete=models.PROTECT) name = models.CharField(max_length=127) The use of ContentType allows me to create relationship types between any pair of models. Finally, I think this is approximately what the relationship would look like (pseudo-code): class Relationship(models.Model): type = models.ForeignKey(RelationshipType, on_delete=models.PROTECT) instance_a_id = models.PositiveBigIntegerField() instance_a = GenericForeignKey("model_a", "instance_a_id") instance_b_id = models.PositiveBigIntegerField() instance_b … -
Mocked Redis counter does not increment between requests for different users
I am testing a Django view that increments recipe view counters using Redis. The logic is: each user can increment recipe views only once different users should increment the counter Redis is mocked using MagicMock The first test passes, and part of the second test passes, but the counter never increments to 2 for the second user, even though I explicitly change mock return values. Django View # recipehub/apps/recipes/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render from recipehub.apps.recipes.models import Recipe from recipehub.redis import r @login_required def recipe_detail(request, slug): recipe = get_object_or_404(Recipe, slug=slug, moderation_status="approved") redis_user_recipe_view_key = f"user:{request.user.id}:recipe:{recipe.id}:view" redis_all_recipe_view_key = f"recipe:{recipe.id}:views" if not r.exists(redis_user_recipe_view_key): r.set(redis_user_recipe_view_key, 1) r.incr(redis_all_recipe_view_key) recipe_views = int(r.get(redis_all_recipe_view_key) or 0) return render( request, "recipes/recipe_detail.html", { "recipe": recipe, "views": recipe_views, }, ) Redis client definition # recipehub/redis.py import redis r = redis.Redis(host="localhost", port=6379, db=0) ** Redis mock fixture** import pytest from unittest.mock import MagicMock @pytest.fixture() def mock_redis(mocker): magic_mock = MagicMock() mocker.patch("recipehub.redis.r", magic_mock) return magic_mock Test 1 — first user increments counter (passes) @pytest.mark.django_db def test_recipe_detail_first_user_view_increments_counter(client, users_list, mock_redis): recipe = RecipeFactory.create(slug="fish", moderation_status="approved") user = users_list["first_simple_user"] mock_redis.exists.return_value = False mock_redis.get.return_value = b'1' mock_redis.incr.return_value = 1 mock_redis.set.return_value = True client.force_login(user) response = client.get( reverse("recipes:recipe-detail", kwargs={"slug": recipe.slug}) ) assertContains(response, '1 views') Test 2 … -
Windows Apache two django projects in separated venv
I need to host two separated apps, with separated venv and separated db, reason cut costs. Both of apps have been developed separately, no I have only single server to host them. core is running on port 80 , portal on 8081 I am able to access both apps at some point of time, remotelly means outside of server. But after some time doesn't matter what port I provide I am able to access only sigle app. Seems static files are served properly as ico is changes, but content is the same so I see portal for example on both ports. nut sure what trigers that and how to prevent it. here are my files. D:\Apache24\conf\httpd.conf Define SRVROOT "d:/Apache24" ServerRoot "${SRVROOT}" Listen 10.192.28.86:80 Listen 10.192.28.86:8081 LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule authn_core_module modules/mod_authn_core.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authz_core_module modules/mod_authz_core.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule cgi_module modules/mod_cgi.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule include_module modules/mod_include.so LoadModule isapi_module modules/mod_isapi.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule setenvif_module modules/mod_setenvif.so <IfModule unixd_module> User daemon Group daemon </IfModule> ServerAdmin admin@example.com <Directory /> AllowOverride … -
PAPERLESS_FILENAME_FORMAT does not modify the files structure into folders
ngx (with Docker) on a Raspberry Pi5 with Trixies with success. After, I uploaded a document, I can see a list of files in this location /paperless-ngx/media/documents/originals -rw-r--r-- 1 pierrot 166300 14 jan 19:59 0000001.pdf -rw-r--r-- 1 pierrot 453908 14 jan 20:09 0000002.pdf -rw-r--r-- 1 pierrot 171460 14 jan 20:25 0000003.pdf -rw-r--r-- 1 pierrot 632003 14 jan 21:33 0000004.pdf -rw-r--r-- 1 pierrot 218267 14 jan 22:02 0000005.pdf -rw-r--r-- 1 pierrot 354021 14 jan 22:12 0000006.pdf -rw-r--r-- 1 pierrot 248148 14 jan 22:20 0000007.pdf -rw-r--r-- 1 pierrot 244836 14 jan 23:11 0000008.pdf -rw-r--r-- 1 pierrot 768796 14 jan 23:19 0000009.pdf I discovered, I can format a structure with the setting PAPERLESS_FILENAME_FORMAT. This PAPERLESS_FILENAME_FORMAT={{created_year}}/{{correspondent}}/{{document_type}}/{{title}} should result with folders structure as: /2025/company/bill/filename.pdf How I process Installation of Docker (quick steps) sudo apt install apt-transport-https ca-certificates curl gpg curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/debian trixie stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null apt-cache policy | grep docker sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin sudo systemctl is-active docker sudo useradd user docker docker ps Installation of Paperless bash -c "$(curl --location --silent --show-error https://raw.githubusercontent.com/paperless-ngx/paperless-ngx/main/install-paperless-ngx.sh)" I mostly keep the default value excepted for the URL … -
Can't send the refresh cookie from my ReactJS frontend to the Django backend
when i login the refresh cookies is set like that : response.set_cookie( key="refresh", value=str(refresh), httponly=True, secure=False, samesite="None", path="/", ) and i tried to do and axios.js file where it verify the access then refresh it when needed like that : // Refresh access token (cookie sent automatically) console.log('trying refresh') const res = await axios.post('http://localhost:8000/refresh/', {}, { withCredentials: true }); access = res.data.access; console.log('Refreshed access token:', access); the problem is the code always gives an error on the line of refreshing, and the backend dont receive a cookie: COOKIES: {} None Unauthorized: /refresh/ [15/Jan/2026 16:48:53] "POST /refresh/ HTTP/1.1" 401 29 all django seetings where set : CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
Random 500 Server Errors On Django 6 Website After Going Live
I've built a small, lightweight website for the first time using Django 6.0 with Python 3.12. There is one page that pulls data from the database, and that page has random 500 internal server errors appear. Refreshing the page will usually display the page as intended. I cannot recreate this error in my development environment; it only happens on my production environment. The error I'm getting in the logs looks like this: ERROR 2026-01-13 11:34:37,581 log 791 124526765520576 Internal Server Error: /menu/ Traceback (most recent call last): File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 198, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/menu/views.py", line 25, in menu return render(request, "menu/menu.html", context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/shortcuts.py", line 25, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/backends/django.py", line 107, in render return self.template.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/base.py", line 174, in render return self._render(context) ^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/base.py", line 166, in _render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/base.py", line 1091, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/base.py", line 1052, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "/var/www/juliasempanadassite/venv/lib/python3.12/site-packages/django/template/loader_tags.py", line 160, in render return compiled_parent._render(context) … -
I want to know how to best get my new service tested
Using AI to build apps Hi all, did this fun project (definitely for fun, absolutely no profit): https://pedestrian.site/ It's a small thing to build Python Django applications with the help of an LLM -- it's based on Mistral -- it actually works fairly well. I need someone to test it out though - how to best go about that? So, the background story is that I've seen my share of applications being built using AI in various forms -- enabling non-techs to create applications is a definitely great. However, often the applications go out on a tangent complexity-wise as everybody wants to build things at 'webscale' -- which is a very subjective measure. This tool however, has a very strict 'system prompt' if you may say so -- you strictly build a Python Django application - you strictly have an SQLite database - there's a lot of decisions taken that will surely need a revisit before you go 'webscale' (by any perceivable metric). _However_ you're almost guaranteed to never end up with dependency and complexity hell, as the path chosen is so narrow and strict. You need not be an SQL-wizard, an infrastructure master or a Typescript specialist -- in … -
Django startproject fails after I manually created the project files/folders (name conflict?)
I’m setting up a Django + Channels project and I think I messed up the order. I ran these commands: cd ~ mkdir social_mvp cd social_mvp mkdir socialsite mkdir core mkdir -p core/templates/core mkdir -p core/static/core/css touch manage.py requirements.txt touch socialsite/__init__.py socialsite/settings.py socialsite/urls.py socialsite/wsgi.py socialsite/asgi.py python3 -m venv venv source venv/bin/activate pip install django channels django-admin startproject socialsite . When I run django-admin startproject socialsite . it errors out (something about files/folders already existing or a conflict). What’s the correct way to do this? Should I not manually create manage.py and the socialsite/ folder first? What’s the right command order for Django + Channels? -
Django admin actions not reflecting on user dashboard and admin privileges are limited
I am working on a Django project where actions performed in the Django admin panel (such as approving users, updating statuses, or modifying records) are not reflecting on the users’ dashboard views. Additionally, admin users seem to have limited privileges despite being marked as is_staff or is_superuser. I suspect issues with permissions, custom queryset filtering, signals, or how the dashboard queries data. How can I correctly synchronize admin actions with frontend dashboards and ensure proper privilege enforcement? -
Django email verification
I have build a django app using rest framework, it includes the email verification using otp.I am receiving the otp when I am deploying it on local host, bt when I deploy the server on any hosting site like render (free hosting) I am not receiving any email and my request gets timed out, if I use the async approach, my api responses "email sent successfully " but I never received any opt. Can anyone help me out from this? -
Why does Celery with Redis backend create hundreds of connections despite max_connections limits
I am using Django + Celery with Redis as both the broker and the result backend. Here is my Celery configuration: # Celery settings CELERY_BROKER_URL = 'redis://redis:6379/1' CELERY_RESULT_BACKEND = 'redis://redis:6379/2' CELERY_BROKER_POOL_LIMIT = 10 CELERY_REDIS_MAX_CONNECTIONS = 10 CELERY_BROKER_TRANSPORT_OPTIONS = {'max_connections': 10} CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS = {'max_connections': 10} CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' WORKER_MAX_MEMORY_PER_CHILD_KB = 200_000 CELERY_WORKER_MAX_MEMORY_PER_CHILD = 200_000 CELERY_WORKER_MAX_TASKS_PER_CHILD = 1000 CELERY_BEAT_SCHEDULE = celery_beat_schedule CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_QUEUES = ( Queue('default'), Queue('bind_status'), ) CELERY_ONCE = { 'backend': 'celery_once.backends.Redis', 'settings': { 'url': "redis://redis:6379/3", 'default_timeout': 60*60, } } app = Celery('') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.worker_send_task_events = True app.conf.task_send_sent_event = True app.conf.task_track_started = True app.conf.result_extended = True app.conf.broker_connection_retry_on_startup = True app.autodiscover_tasks() I launch my workers like this: celery -A giberno worker -Q bind_status --loglevel=info -P gevent -c 4 Expected Behavior Given the max_connections=10 settings, I expected the total number of TCP connections to Redis (broker + result backend) to be around 10–20, especially with concurrency=4. Observed Behavior When I check the number of connections to Redis DB 2 (used as the result backend), I see hundreds of connections (100–400) even though the `max_connections` limits are set. Questions Why does Celery create so many connections despite the max_connections limits? How can I correctly limit …