Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I test my Django & React app with massive users efficiently?
I'm working on a Django backend and a React frontend, and I need to test my app with a large number of users. I have used Cypress for UI testing, but it takes too much time to complete the tests I need. My goal is to test two different scenarios: First scenario (8,840 users) Register a user Modify user details Create a contribution Second scenario (~300,000 users) Perform the same process as the first scenario but on a much larger scale I'm looking for a faster and more efficient way to execute these tests. -
Initiate paypal payment post request returning 404 error, but the url mapping in django backend is correct, no syntax errors in React frontend
My React and Django website is deployed on render, when i run the backend service from render the initiate paypal payment url is mapped there, i also checked Django urls its there, but when i send the post request from the frontend, i get a 404 error and iyour text checked properly i have no syntax errors, am sending the correct data to the backend, forward slash is there. Am using Sandbox mode, i removed the client id and secret id from settings.py and i placed them in render's environment variable, so this is how i access them: PAYPAL_CLIENT_ID = os.getenv('PAYPAL_CLIENT_ID') PAYPAL_SECRET_CLIENT = os.getenv('PAYPAL_SECRET_CLIENT') i feel like whenever i click on the 'pay with Paypal button' so as to send the request, something blocks it hence the 404 error. website link, please you can use fake filter extension to login and help me checkout the problem Also : No CORS-POLICY issues the frontend Url is correctly placed in the allowed origins the REACT_BASE_URL is also correctly placed in my settings.py and views.py i just don't no what the problem is, i have so far tried everything, any one who can help me, i appreciate thank you backend code @api_view(['POST']) def … -
Django shell: Can't find constructor of a model
I have a Django Modell Kunde from django.db import models class Kunde(models.Model): Kundennummer = models.IntegerField(), Vorname = models.CharField(max_length=200), Nachname = models.CharField(max_length=200) I open the Django shell with the command python manage.py shell I do from kundenliste.models import Kunde; and then Kunde.objects.all() This gives me <QuerySet []> Now I would like to insert a new customer But k1 = Kunde(Kundennummer=1,Vorname="Florian",Nachname="Ingerl"); gives me the error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\imelf\Documents\NachhilfeInfoUni\MaxPython\env_site\Lib\site-packages\django\db\models\base.py", line 569, in __init__ raise TypeError( TypeError: Kunde() got unexpected keyword arguments: 'Kundennummer', 'Vorname' What do I do wrong? -
Python: Can't find command virtualenv
I have the python installed from here: Python download link The command python --version gives me Python 3.12.2 I want to create a virtual environment in order to use it for a Django project. pip install virtualenv works fine. But afterwards , the command virtualenv env_site gives me the error virtualenv : Die Benennung "virtualenv" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang. In Zeile:1 Zeichen:1 + virtualenv env_site + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException In my path variable, I have the following entries C:\Software\Python\Python312\Scripts\ C:\Software\Python\Python312\ C:\Users\imelf\AppData\Local\Programs\Python\Launcher\ What is wrong? Why doesn't he recognize the command virtualenv ? -
Cant find command virtualenv env_site
I have the python installed from here. www.python.org/downloads the command python --version gives me Python 3.12.2 I want to create a virtual environment in order to use it for a Django project. pip install virtualenv work fine, but afterwarnds, the command virtualenv env_site gives me the error: virtualenv : Die Benennung "virtualenv" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang. In Zeile:1 Zeichen:1 virtualenv env_site + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException In my path variable, I have the following entries. C:\Program Files\Python313\Scripts\ C:\Program Files\Python313\ C:\Users\Max\AppData\Local\Programs\Python\Launcher\ If someone can help me, that would be nice. -
Custom text in Django admin is not translating
I have a Django project where I need to localize the admin panel into two languages. It seems like I'm following the instructions, but for some reason, my custom translation isn't working. Below, I’ve attached the configuration files. #settings.py USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [BASE_DIR / "locale"] LANGUAGE_CODE = "ru" LANGUAGES = [ ("ru", _("Русский")), ("en", _("Английский")), ] #urls.py urlpatterns = [ path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns(path("admin/", admin.site.urls)) And specifically the usage #models.py from django.utils.translation import gettext_lazy as _ class Bot(models.Model): session_name = models.CharField(_("Имя сессии")) .po file #locale/en/LC_MESSAGES/django.po ... #: src/backend/bots/models.py:8 msgid "Имя сессии" msgstr "Session name" .po file compiled with the command python manage.py compilemessages In the admin panel, when changing the language, everything is translated except my custom translations. I also tried running the check through the shell. #Django shell from django.utils.translation import gettext as _, activate, get_language activate("en") print(_("Имя сессии")) # Имя сессии It feels like Django is ignoring my .po file And files tree . ├── locale │ └── en │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── manage.py ├── src │ ├── backend │ │ ├── core │ │ │ ├── __init__.py │ │ │ ├── … -
¿Cual es mejor en realizar consultas de bases de datos?
Estoy desarrollando una aplicación web con Django y necesito optimizar las consultas a la base de datos. ¿Cuál es la mejor práctica para mejorar el rendimiento en consultas SQL en Django ORM? -
Django app with Azure storage account - images are not saved to blob storage container
I have a Django app, and I am trying to store images in an Azure Storage account. I have a database with table category and property name images, where the URL of the uploaded image is saved when a user uploads an image. For example: media/photos/categories/Koesimanse.png However, the image is not being saved in the Azure storage container. When I try to access the URL: https://dier.blob.core.windows.net/media/media/photos/categories/Liza_GUAzhRg.jpeg Then I get this error: BlobNotFound The specified blob does not exist. RequestId:2bf5ff31-201e-0066-459e-a4a58e000000 Time:2025-04-03T13:45:48.5890398Z Additionally, when I check the blob container, the image is not there. However, if I manually upload an image to the Azure blob container and store its URL in the database, the image is successfully retrieved from Azure Storage blob container. So for the models I have this: class Category(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name="Naam") description = CKEditor5Field( max_length=11000, blank=True, null=True, verbose_name="Beschrijving", config_name="extends") images = models.ImageField( upload_to="media/photos/categories", blank=False, null=False, verbose_name="Foto") # Define the cropping field cropping = ImageRatioField('images', '300x300') category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='subcategories', blank=True, null=True, verbose_name="Categorie") date_create = models.DateTimeField( auto_now_add=True, verbose_name="Datum aangemaakt") date_update = models.DateTimeField( auto_now=True, verbose_name="Datum geupdate") def img_preview(self): if self.images and self.images.name: try: if self.images.storage.exists(self.images.name): print("IMAGES SAVED") print(self.images) return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') else: … -
Django superuser privileges
I am following Vincent's book, Django for Beginners, and I am on chapter 14. I have followed all the tutorial code to create a superuser and have granted it all of the permissions in the admin panel. However, when logged in as the superuser I am not able to delete or edit the posts of other users. Should the superuser be able to do this? Thank you for any insight. -
django.core.exceptions.ImproperlyConfigured:
I get this error all the time since two days now and i am stacked at this level? I am a beginner with django and i read the django documentation following all the instructions but always the same problem. Hello, I get this error all the time since two days now and i am stacked at this level? I am a beginner with django and i read the django documentation following all the instructions but always the same problem. django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pages.urls' from 'C:\Users\adech\mon_site\monsite\pages\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
django Pannel error Could not reach the URL. Please check the link
Here when i update my model i am getting this error why ? This is my models.py class ProductImage(models.Model): user = models.ForeignKey(Seller,on_delete=models.CASCADE, related_name='Product_Image_User') Video = models.FileField(upload_to="Product/video", blank=True, null=True) images = models.JSONField(default=list) # Stores multiple image URLs Date = models.DateTimeField(default=timezone.now) Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images", blank=False, null=False) secret_key = models.TextField(blank=True,null=True) def __str__(self): return f"{self.user}-{self.Product}-{self.id}" -
Django project - Redis connection "kombu.exceptions.OperationalError: invalid username-password pair or user is disabled."
Hello I'm trying to deploy my django app on railway. This app is using Celery on Redis. When I deploy the project the logs indicate: [enter image description here][1] As we see the initital connection is to redis is successful. However I as soons as I trigger the task (from my tasks.py file): the connection is lost: [enter image description here][2] The error indicates a "invalid username-password pair or user is disabled.". Nevertheless, I don't understand because my REDIS_URL is the same used for the initial connection when the project is deployed. In my logs I get extra info: [enter image description here][3] [1]: https://i.sstatic.net/3yAjMwlD.png [2]: https://i.sstatic.net/Cb0cY3Lr.png [3]: https://i.sstatic.net/XWwOvWdc.png tasks.py # mobile_subscriptions/tasks.py from celery import shared_task import time import logging logger = logging.getLogger(__name__) @shared_task def debug_task(): try: logger.info('Demo task started!') time.sleep(10) logger.info('Demo task completed!') return 'Demo task completed!' except Exception as e: logger.error(f"Unexpected error in debug task: {e}") raise celery.py: # comparaplan/celery.py import os from celery import Celery from dotenv import load_dotenv load_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'comparaplan.settings') celery_app = Celery('comparaplan') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() celery_app.conf.task_routes = { 'mobile_subscriptions.tasks.debug_task': {'queue': 'cloud_queue'}, } celery_app.conf.update( result_expires=60, ) settings.py """ Django settings for comparaplan project. """ import os import sys import time from pathlib import Path from … -
Django Select2 Autocomplete: How to Pass Extra Parameter (argId) to the View?
I'm using Django with django-autocomplete-light and Select2 to create an autocomplete field. The Select2 field is dynamically added to the page when another field is selected. It fetches data from a Django autocomplete view, and everything works fine. Now, I need to filter the queryset in my autocomplete view based on an extra parameter (argId). However, I'm not sure how to pass this parameter correctly. JavaScript (Select2 Initialization) function getElement(argId) { let elementSelect = $("<select></select>"); let elementDiv = $(`<div id='element_id' style='text-align: center'></div>`); elementDiv.append(elementSelect); $(elementSelect).select2({ ajax: { url: "/myautocomplete/class", data: function (params) { return { q: params.term, // Search term arg_id: argId // Pass extra parameter }; }, processResults: function (data) { return { results: data.results // Ensure correct format }; } }, placeholder: "Element...", minimumInputLength: 3 }); return elementDiv; } Django Autocomplete View class ElementAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView): def get_queryset(self): qs = MyModel.objects.filter(...) I want to pass argId from JavaScript to the Django view so that the queryset is filtered accordingly. However, I am not sure if my approach is correct or how to achieve this. Appreciate any suggestions or improvements. Thanks! -
I do not understand why in Django Rest Framework, my serializer do not serialize the file I gave it
I do not understand why in Django Rest Framework, my serializer do not serialize the file I gave it I do a request like this in my Vue.js file: const formData = new FormData(); formData.append("file", file.value); formData.append("amount_pages", "" + 12); try { const response = await fetch(BACKEND_URL, { method: "POST", body: formData, }); } catch (e: any) { console.error(e); } On a view like that in my Django/DRF app: from rest_framework import generics, serializers class MySerializer(serializers.Serializer): file = serializers.FileField(required=True) amount_pages = serializers.IntegerField() class Meta: fields = [ "file", "amount_pages", ] class MyView(generics.CreateAPIView): def post(self, request, *args, **kwargs): serializer = MySerializer(data=request.data) print(request.data) # <QueryDict: {'file': [<TemporaryUploadedFile: part1.pdf (application/pdf)>], 'amount_pages': ['12']}> print(serializer.data) # {'file': None, 'amount_pages': 12} I have already took a look at other issues but have not found any answers. -
Security on Webapp against hacking attempts
I hava a under-construction django webapp on Heroku. While checking the latest features on the logs, I read a great deal (several hundreds) of rapid succesion GET request, asking for passwords, keys, and other sensible credentials. This is new, we are only 2 people working daily on the website, and it makes no sense as the WebApp doesnt ask and doesnt have these credential, so they are hacking attempts. I know nothing about web security. Sorry if I am asking or saying obvious or wrong things My questions are: what to do now ? How do I prenvent these specific attacks from happening and been sucesfull ? How do I prevent other common attacks from happening and been sucesfull ? How can assets the webapp vulnerabilities ? I wrote the fwd="latest_ip" on https://www.iplocation.net/ip-lookup trying to know from where the attacks came from, but it shows widely different results. I imagine that I need a Firewall. But I dont know which rule I should apply, or if there is an option to protect from django (instead of the firewall), or other option. Reading https://devcenter.heroku.com/articles/expeditedwaf it seems that : CAPTCHA protection rule for the entire site (enter / as the URL) Country … -
Custom sorting of the Django admin panel sidebar
I need to sort the items in the admin panel sidebar in a desired order. I am attaching the image to better understand the problem. enter image description here I also read the Django documentation, the Custom Admin section, but I didn't find anything about this. -
Javascript mystery error - Event listener does not fire
JavaScript gods! I have a JS code here which does not work. Could someone please point out what I'm doing wrong here? In the code below, the loadCountryList() function is called and I see a list of countries in the HTML datalist element. But the event listeners, responsible for detecting the changes in the input field does not work. When I call the loadRegionList() function outside of the event listener, I get a proper server response. I am instantiating the class inside another file like this: if (document.querySelector(".rooms-page")) { // Room country filter new RoomRegionFiter( "id_country_input", "country_datalist", "region_datalist", csrftoken); } class RoomRegionFiter { constructor (id_country_input, country_datalist, region_datalist, csrftoken) { this.input = document.getElementById(id_country_input); this.country_dataList = document.getElementById(country_datalist); this.region_datalist = document.getElementById(region_datalist); this.csrftoken = csrftoken; this.initializeCountryEventListeners(); } initializeCountryEventListeners() { this.loadCountryList() this.input.addEventListener("change", () => { console.info("Listening for changes") const selected_country = this.input.value; this.loadRegionList(selected_country); }); this.input.addEventListener("input", () => { console.info("Listening for input") const selected_country = this.input.value; this.loadRegionList(selected_country); }); }; // Loads all the countries on page load async loadCountryList() { const protocol = window.location.protocol; const hostname = window.location.hostname; const port = window.location.port; const endPoint = `${protocol}//${hostname}:${port}/roomfiltercountry/`; try { const response = await fetch(endPoint, { method: "GET", headers: { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": this.csrftoken } }); … -
How to change field Model attributes when inheriting from abstract models
In my code, I use a lot of abstract Model classes. When I inherit from them, I often need to change some of the attributes of specific fields. I am trying to implement a solution where those attributes are defined as class variables which can then be overridden upon instantiation. Here is a simple example of what I am trying to do: Let's say we have an abstract model class as such: class AbstractThing(models.Model): MAX_LENGTH = 1000 IS_UNIQUE = True name = models.CharField(max_length=MAX_LENGTH, unique=IS_UNIQUE) class Meta: abstract = True What I am hoping to do is this: class RealThing(AbstractThing): IS_UNIQUE = False MAX_LENGTH = 200 However it does not work. The resulting migration file looks like this: migrations.CreateModel( name='RealThing', fields=[ ('id', models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField( max_length=1000, unique=True) ), ], options={ 'abstract': False, }, ), Is this just not possible or am I doing something incorrect? Any ideas would be really appreciated. -
Create a New Django Web App with MS Sql Server as backend db
Recently while working with several powerapp applications we noticed that the applications were becoming slow day by day. The main reason behind this slowness is increasing amount of data validations on every single page and increase in data. We came up with the decision of creating a Django web app to replace the existing poweapp apps. Now while researching, i came to know that django doesnot have out of box support for Ms Sql Server. Also i cannot create a new DB on my server as migrating tables from old db to new db will require lot of approvals. is there a way i can utilize my existing db i know we can use django-mssql-backend and few other 3rd party mssql packages. But will i be able to trigger storer procedure and run other sql commands and fetch data using select statements -
ManyToMany with through: ForeignKey not showing in admin
I have a ManyToManyField using through: class Entity(models.Model): relationships = models.ManyToManyField('self', through='ThroughRelationship', blank=True) class ThroughRelationship(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE) name = models.CharField() I'm adding it to admin like this: class ThroughRelationshipInline(admin.TabularInline): model = ThroughRelationship extra = 3 @admin.register(Entity) class EntityAdmin(admin.ModelAdmin): inlines = [ThroughRelationshipInline] However, in the admin panel, only the name field is showing, I can't select an entity. How can I fix this? -
Trying to understand Wagtail CMS internals: where is the template variable allow_external_link defined?
I have difficulties in understanding how the modal dialog that allows to insert different Link types into a richtext field functions. Specifically in this file: https://github.com/wagtail/wagtail/blob/main/wagtail/admin/templates/wagtailadmin/chooser/_link_types.html The allow_xyz parameters: where are they set? E.g.: {% elif allow_external_link %} Where/when is allow_external_link defined or set to True? Thanks in advance -
How to display multiple formsets in one another?
On the Site Form is used to give data to a case but since there can be multiple on a site it is made as a formset. In addition, each case can have multiple m2m relations, which are also a formset. The second formset therefore can be used for each of the first formsets. But how to GET and POST data there? Can prefixes made dynamically or is there a whole other way around? My current approach is to have both formsets as such but have the second one with an iterated prefix. view.py def rezept_lookup(request, my_id): b = Auftrag.objects.filter(id=my_id).first().messung_auftrag.all().count() InhaltFormSet = formset_factory(InhaltForm, extra=5) FormulierungFormSet = formset_factory(FormulierungForm, extra=0) q = Auftrag.objects.filter(id=my_id).first().messung_auftrag.all() b = [x.messung_rezept for x in q] formset = FormulierungFormSet(request.POST or None, prefix="rezept", initial=[{'bindemittel_name': x.bindemittel_name, 'messung_id': x.messung_id, 'bindemittel_menge': x.bindemittel_menge, 'untergrund_name': x.untergrund_name, 'schichtdicke': x.schichtdicke, 'isActive': x.isActive, 'rezept_name': x.rezept_name } for x in b]) formset_inline = InhaltFormSet(request.POST or None, prefix=[f"inhalt_{n}" for n in range(0,5,1)]) if request.method == "POST": if formset.is_valid(): for form in formset: temp = form.save(commit=False) temp.save() context = { "formset":formset, "formset_inline":formset_inline, } return render(request, "template.html", context) template.html <form method="post" action="{% url 'Farbmetrik:rezept_lookup' my_id=my_id %}"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_field_errors }} {{ formset_inline.management_form }} {{ formset_inline.non_field_errors }} … -
django-allauth - new users signed up via Microsoft integration trigger "No exception message supplied"
I've been working on an integration using django-allauth with Microsoft (EntraID) to allow SSO and it's working well for existing users with their accounts being matched on email address however when a new user goes through the flow I'm receiving the following exception No exception message supplied which is raised by site-packages/allauth/account/utils.py, line 227, in setup_user_email, raised during allauth.socialaccount.providers.oauth2.views.view. If the same user then goes back through the SSO sign-in flow then it works as it matches the account and they get through. Below are the combination of configuration settings I have in settings.py, the app itself is configured via Django Admin SOCIALACCOUNT_PROVIDERS = { "microsoft": { "APPS": [], "EMAIL_AUTHENTICATION": True, "VERIFIED_EMAIL": True, } } ACCOUNT_LOGIN_METHODS = {"email"} ACCOUNT_SIGNUP_FIELDS = ["email*"] ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = True SOCIALACCOUNT_EMAIL_REQUIRED = True I've set the settings above based upon the following two configuration setting pages (https://docs.allauth.org/en/latest/account/configuration.html and https://docs.allauth.org/en/latest/socialaccount/configuration.html ) and upon my understanding that these combinations of settings should ensure that existing accounts are matched via email address, that the user will be automatically signed in when matched and that new accounts will be automatically created without showing the sign-up … -
The layout doesn't change at all in browsers. Django 5.0, Bootstrap from two years ago
I returned to the project that I developed 2 years ago. I launched it in production, everything works. I'm trying to fix something in the layout, but any changes in the Django template are not accepted by the browser. Tried different browsers. No changes either on the local machine or on production. You can comment out the entire page, but nothing happens - the browser returns the page in the form in which I launched the project the first time. Tried resetting the cache in different ways: ctrl+shift+R, ctrl+shift+DEL, through DevTools. I don't understand at all what the problem could be. Please help me figure it out. Thanks in advance for any answer. -
I am looking for a realtime project that backends Django and Frontend React. Help me
I want to build a real-time chat application using Django for the backend and React.js for the frontend. Since I’m new to both frameworks, I need a clear example or a step-by-step guide to implement real-time features (like WebSockets or Django Channels). Could you provide a basic code structure for both backend (Django) and frontend (React) to establish real-time communication? Additionally, what tools or libraries (e.g., REST APIs, Axios, WebSocket configurations) are essential for this integration? Thank you I want to build a real-time chat application using Django for the backend and React.