Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django session data lost
I am new to Django, so forgive me for any beginner mistakes. I am experiencing an issue where the session data is being lost when a user tries to navigate on my site after logging in. I am making this website on W3Schools (I know it's not a great resource already), and have attached some images of my code home html code and some of my views. Specifically, I will log a user in successfully and the user is sent back to the home page with their session info intact, but as soon as I press the home button on the navbar or any other implemented buttons the session info is lost. In the database, the session info is still there, so it has not been deleted, just lost. Thanks for the help! [enter image description here](https://i.sstatic.net/wi7dLWnY.png) [enter image description here](https://i.sstatic.net/E42uA8IZ.png) [enter image description here](https://i.sstatic.net/VCyNa8Kt.png) I logged some messages to confirm that the session data was lost after being sent to the URLs 'profile' and 'home' from the home page. I do not mess with session data anywhere other than logging the user in. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in Django connection with PostgreSQL in Docker
I am trying to connect my Django application to PostgreSQL running in a Docker container, but when I execute python manage.py runserver or python manage.py makemigrations, I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 85: invalid continuation What I've tried: Verified that the database uses UTF-8. Deleted and recreated the database in Docker with UTF-8. Tested with both psycopg2 and psycopg2-binary. Checked for special characters in my configuration. Deleted and reinstalled my virtual environment. What else can I check to resolve this error? Could there be some data in the database causing this issue? How can I debug which exact byte is triggering this error in PostgreSQL? -
Unable to Upload Images in Django Project on AWS S3, despite configuring ImageField and storages
I’m working on a Django project, and I’ve successfully connected it to AWS S3 for storing media files. However, I’m unable to upload images via the Django Admin Panel. Text-only articles are uploaded fine, but as soon as I try to upload an image, it causes issues and the upload fails. I've configured the ImageField in my model and set up AWS S3 storage, but the image uploads still don't work. class Article(models.Model): CATEGORY_CHOICES = [ ('TECH', 'Technology'), ('PHI', 'Philosophy'), ('SCI', 'Science'), ('CUL', 'Culture'), ('BUS', 'Business'), ] title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=100) published_date = models.DateTimeField(default=now) is_published = models.BooleanField(default=False) # Control publishing status image = models.ImageField(upload_to='articles/', blank=True, null=True) is_featured = models.BooleanField(default=False) category = models.CharField(default= False, max_length=10, choices=CATEGORY_CHOICES) def __str__(self): return self.title AWS S3 Bucket Permissions: I’ve ensured that my AWS S3 bucket is set to allow public access, and the necessary permissions for writing objects are in place. STATIC_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com/static/" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com/media/" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com/media/" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': getenv('PGDATABASE'), 'USER': getenv('PGUSER'), 'PASSWORD': getenv('PGPASSWORD'), 'HOST': getenv('PGHOST'), 'PORT': getenv('PGPORT', 5432), 'DISABLE_SERVER_SIDE_CURSORS': True, } } DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Troubleshooting: I’ve confirmed that the Django application has internet access to AWS S3. I’ve verified …