Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Elastic Beanstalk not detecting RDS environment variables (falls back to SQLite)
I am deploying a Django app to AWS Elastic Beanstalk and connecting it to an RDS PostgreSQL database. My Django settings are configured to use PostgreSQL only if RDS_DB_NAME exists in os.environ, otherwise it falls back to SQLite. However, even though RDS environment variables are defined in Elastic Beanstalk, Django behaves as if they are not present and falls back to SQLite. settings.py if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Elastic Beanstalk Environment Variables (from console) Under Configuration → Environment properties: RDS_DB_NAME=ebdb RDS_USERNAME=vividvaultdb RDS_PASSWORD=******** RDS_HOSTNAME=awseb-xxxxx.ap-south-1.rds.amazonaws.com RDS_PORT=5432 All variables are clearly visible in the EB console. django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: vividvault.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static db-migrate.config container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: vividvault.settings .elasticbeanstalk/config.yml branch-defaults: main: environment: vividvault-env global: application_name: vividvault-project default_platform: Python 3.11 running on 64bit Amazon Linux 2023 default_region: ap-south-1 profile: eb-cli sc: git workspace_type: Application The Problem When I SSH into the instance and open Django shell: eb ssh cd /var/app/current source /var/app/venv/*/bin/activate python3 manage.py shell Then check: import os print("RDS_DB_NAME … -
How to synchronize a locale until a defined level/page
I’d like to keep the locale synchronization mostly as it is, but I’d like to tell wagtail-localize to ignore all pages under, say, Lessons: Root > Units > Lessons || [lesson 1] So that lesson pages created under Lessons won’t get automatically created in the other locales. Is that possible? -
Why am I getting this key error when using django-formtools and django-allauth together
So I am trying to create multi-step signup wizard using django-formtools and django-allauth. I am using the SessionWizardView from formtools and just trying to use allauth's functionality for signup. I'm not using its standard one page signup flow or its form classes or default signup template. I believe I have most things configured and setup correctly, however, I keep getting this error from django when I go to /accounts/signup/ KeyError at /accounts/signup/ 'email_step' Exception Value:'email_step' it happens on line 50 in the views.py file, which is this line: return [TEMPLATES[self.steps.current]] I will leave out the imports for brevity sake, but below you will find all the relevant code, should you need more, just ask. in my settings.py: # allauth settings for dev for now ACCOUNT_EMAIL_VERIFICATION = 'optional' ACCOUNT_SIGNUP_FIELDS = ['email*', 'password1*', 'password2*'] ACCOUNT_LOGIN_METHODS = {'email'}ACCOUNT_UNIQUE_EMAIL = TrueACCOUNT_LOGIN_METHODS = {'email'} ACCOUNT_USER_MODEL_USERNAME_FIELD = NoneACCOUNT_LOGOUT_REDIRECT_URL = '/' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' LOGIN_REDIRECT_URL = '/' ACCOUNT_ADAPTER = 'users.adapters.CustomAccountAdapter' # telling allauth what forms to use ACCOUNT_FORMS = { 'signup': 'users.forms.EmailForm', ...} in my forms.py: class EmailForm(forms.Form): email = forms.EmailField(max_length=255, required=True, label='Email') class PasswordForm(forms.Form): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password … -
How to hide GraphQL exceptions in strawberry and Django?
I am using GraphQL with strawberry in my Django project. When an exception is raised, the error is shown in the terminal like the server errors. But if a user make mistakes while creating a query, It shouldn't show like this. Here is one of the errors. GraphQL request:18:5 17 | # } 18 | register(name: "Mahmuud Hasan", email: "test@gmail.com", password: "admin"){ | ^ 19 | success Traceback (most recent call last): File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/graphql/execution/execute.py", line 523, in execute_field result = resolve_fn(source, info, **args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/schema/schema_converter.py", line 778, in _resolver return _get_result_with_extensions( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/schema/schema_converter.py", line 765, in extension_resolver return reduce( ^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/schema/schema_converter.py", line 760, in wrapped_get_result return _get_result( ^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/schema/schema_converter.py", line 717, in _get_result return field.get_result( ^^^^^^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/types/field.py", line 232, in get_result return self.base_resolver(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/env/lib/python3.12/site-packages/strawberry/types/fields/resolver.py", line 250, in __call__ return self.wrapped_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mahmud/Projects/Alyve/main/mutations.py", line 47, in register raise GraphQLError("Email already in use.", extensions={"code": "BAD_USER_INPUT"}) graphql.error.graphql_error.GraphQLError: Email already in use. I don't want to show this kinds of errors in my terminal. I have tried to make custom error messages and returned as response instead of raising exceptions. But the front-end developer is using Apollo Client and it can't recognize the errors … -
Since the update to python 3.13 there are some problem with the connection Django and MariaDB
at the moment I want to upgrade the python version from 3.12 to 3.13. The project is run in the docker and uses pipenv. Since the update I have same problems with building the wheel for mysqlclient. I hope you can give me some tips how I can fix this. Under this I give you some information about how I config the connection. Extract of the dockerfile: # install build requirements RUN addgroup --gid 1001 --system app && \ adduser --home /app --shell /bin/false --disabled-password --uid 1001 --system --group app && \ apt-get update && \ apt-get install -y --no-install-recommends \ python3-dev \ default-libmysqlclient-dev \ pkg-config \ libssl-dev \ build-essential I use the 2.2.7 version of mysqlclient and defined it in my Pipefile and pyproject.toml. Here are the settings_prod.py file where the connection to MariaDB is defined. If you need more Information feel free to ask. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME', 'wikoda'), 'USER': os.getenv('DB_USER', 'root'), 'PASSWORD': os.getenv('DB_PASSWORD', ''), 'HOST': os.getenv('DB_HOST', 'testdb'), 'PORT': int(os.getenv('DB_PORT', 3306)), 'TEST': { 'NAME': os.getenv('DB_TEST_NAME', 'test_' + os.getenv('DB_NAME', 'wikoda')), 'USER': os.getenv('DB_TEST_USER', 'root'), 'PASSWORD': os.getenv('DB_TEST_PASSWORD', os.getenv('MYSQL_ROOT_PASSWORD')), } } } -
Django add to cart function
how i create add to cart function? Using request.method or perform an action when click add to cart button? html <form method="post" action="" class="w-full"> {% csrf_token %} <div class="m-3"> <label for="quantity" class="font-bold">Quantity:</label> <input min="0" max="{{item.stock}}" value="1"> </div> <div class=" gap-3 justify-center"> <button type="submit" ">Add to cart</button> <a href="" class="">View cart</a> </div> </form> models.py class Cart(models.Model): cart_id = models.CharField(primary_key=True) total = models.DecimalField(max_digits=9, decimal_places=2) quantity = models.IntegerField() user = models.OneToOneField(User,on_delete=models.CASCADE) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) user = models.OneToOneField(User,on_delete=models.CASCADE) -
How can I use Django Allauth and Google Identity Services (GSI) simultaneously for Google login?
I have a Django project where I want to support Google login in two ways: Classic OAuth redirect flow using Django Allauth. Google One Tap / GSI login. I tried using the same Google OAuth client ID for both flows. The GSI One Tap login works. The Allauth button login now fails with: Access blocked: This app’s request is invalid Error 400: redirect_uri_mismatc I tried: - Using data-login_uri pointing to {% url 'google_login_by_token' %} for GSI. - Keeping {% provider_login_url 'google' %} for Allauth. I want to keep both login methods on the same site: GSI One Tap (token-based) Allauth OAuth redirect (classic button) Thank you for any suggestions -
how to create a custom activity logs of user
i ma making a help moduel and i want activity logs for this Audit trail Who created which user Who updated what field Company activity history CRM history Help module tracking -
Can this query be expressed in Django?
Apologies for the lack of conciseness in formulating this question - part of the problem is that I'm not a database expert and am unsure of the proper terminology for what I'm trying to do. I have the following set of models (simplified and renamed for the purpose of this question). A lot of other functionality has already been built on top of them so wholesale changes aren't possible, though small tweaks could be. class Customer(models.Model): # Company-specific ID format, used everywhere customerId = models.CharField(primary_key=True, max_length=9) name = models.CharField() email = models.CharField() ... class Trip(models.Model): """An event that customers may sign up for - think of a coach tour around Italy, for example.""" name=models.CharField() description=models.CharField() ... class Product(models.Model): """Anything that Customers can buy. This could be as significant as a hotel booking, or as small as a branded keyring.""" # All the Products we're concerned about here have codes, but there do # exist in the database some ad-hoc pseudo-products that don't. code = models.CharField(unique=True, null=True) ... class Payment(models.Model): # Various fields to do with banking, financial tracking, etc. The # relevant one for us is: is_paid = models.BooleanField(default=False) class Purchase(models.Model): """The fact of a Customer buying a Product""" # … -
Django , save_model , admin
okay the issue i am facing is that i am being able to add and save a user , no problem in that and once created , than i can easily assign therapist to that user again no problem , the problem arises when i try to assign the user with a therapist while creating the user , i am realy not getting that where am i making the mistake i mean , i have this feeling that i am assigning things to the user before even creating it but i cant find out which block of code is doing so or maybe just maybe the save_model is working in such a manner that that block code or block of codes need to be rearranged , kindly guide me def save_model(self, request, obj, form, change): # If this is an existing instance and ending is set, prevent changing treatment_therapist if change and obj.client_current_status in UserJourneyStatus.ending_status() and 'treatment_therapist' in form.changed_data: return # Don't save the change to treatment_therapist if 'treatment_therapist' in form.changed_data: # If this is the first time assigning a therapist if not obj.therapist_assigned_at and obj.treatment_therapist: obj.therapist_assigned_at = now() # If changing to a new therapist, update the assignment date … -
Managing Database Connections in a Microservice Architecture with Django
I am designing a microservice architecture using Django and I have encountered a major challenge in data management. I would appreciate it if you could share your experience and perspective. We have several separate services, each with its own database. For example: Core service: Responsible for managing core models such as User and uses the db_core database. WebSocket service: Responsible for managing real-time communications and uses the db_websocket database. Main challenge: How can we best manage the data connection between these two services? This challenge has two aspects: Read Access: The WebSocket service needs to read information from the User model of the Core service to authenticate the user (when connecting) or display his information (for example, the user's name next to a chat message). What is the correct approach for this? Managing Cross-Database Relationships: This challenge is more complex. Suppose we have a ChatMessage model in the WebSocket service that requires a ForeignKey to the User model in the Core service. Since it is not possible to create a FOREIGN KEY constraint between two physical databases, what is the recommended pattern for implementing this logical relationship? -
Telegram OAuth with django
im trying to integrate telegram oauth into my application, currently it successfully log in in telegram, but django doesnt received any data in callback, I have tryied many methods, but without any results views.py def telegram_callback(request): data = request.GET.dict() print('Telegram callback data:', data) if not verify_telegram_auth(data): return HttpResponseBadRequest("Invalid Telegram auth") telegram_id = data["id"] username = data.get("username", f"tg_{telegram_id}") first_name = data.get("first_name", "") last_name = data.get("last_name", "") user, created = User.objects.get_or_create( username=f"tg_{telegram_id}", defaults={ "first_name": first_name, "last_name": last_name, }, ) print(user, telegram_id) login(request, user) return HttpResponseRedirect(reverse("home")) urls.py path("telegram/login/", views.telegram_callback, name="telegram"), and my html <div class="w-full flex justify-center mb-3"> <script async src="https://telegram.org/js/telegram-widget.js?22" data-telegram-login="bot_username" data-size="large" data-radius="12" data-onauth="onTelegramAuth(user)" data-userpic="true" data-lang="en" data-auth-url="{% url 'users:telegram' %}" data-request-access="write"> </script> </div> -
Django project assistance [closed]
When I am creating a new Django project on PyCharm and Choosing to create it in a new enviornment using virtualenv Inheriting all global site packages and making available to all projects Choosing template language Django, template folder templates and application name Manovijay Why does the structure of the new project created not involve the folder named development? -
Best practices for structuring Django REST APIs for maintainability and scalability
I am building a Django-based backend for an e-commerce project with multiple models and REST API endpoints. I want to follow clean architecture and maintainability best practices. How should I structure views, serializers, and URLs for scalability and easier debugging? Tags: Python, Django, REST-API, Backend -
looking for face recognition and validation for registration
We’re building a registration flow where users upload a face image (stored on S3, backend gets the URL). We need to validate that the image has one clear face and check for possible duplicate faces across existing users; if similarity crosses a threshold, we block auto-approval and send it for admin review. We don’t want to build or train ML models and prefer a managed, production-ready AWS solution. **Currently considering AWS Rekognition ,is this the right approach, or are there better alternatives? techstack-Django,react** -
Django static files settings
In my app i combine Django and FastAPI. So I start my django server this way: from fastapi import FastAPI from django.core.asgi import get_asgi_application app = FastAPI() app.mount("/dj", get_asgi_application()) But when i open Django Admin panel i get many errors like: "GET /dj/static/admin/css/dashboard.css HTTP/1.1" 404 Not Found. How should i configure Django static files to get proper Admin panel? -
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(): ^^^^^^^^^^^^^^^^^^^^ …