Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unexpected behaviour with django with django channels
class SessionTakeOverAPIView(generics.GenericAPIView): """ This API view allows a human or AI to take over a chat session. The view handles session takeover validation, updates the session state, and broadcasts relevant events to the chat group. A POST request is used to trigger either a human or AI takeover of a session. Authentication is required to access this view. """ def __init__(self, **kwargs): super().__init__(**kwargs) self.room_group_name = None permission_classes = [BotUserHasRequiredPermissionForMethod] post_permission_required = ['session.reply_session'] queryset = Session.objects.select_related('bot').all() serializer_class = SessionTakeOverSerializer def get_object(self): """ Retrieves the session object based on the session_id provided in the request data. Raises a 404 error if the session is not found. """ try: return super().get_queryset().get(session_id=self.request.data.get('session_id')) except Session.DoesNotExist: raise Http404 # Return 404 error if session not found def handle_human_take_over(self): """ Handles the logic when a human takes over the chat session. It performs the following: - Validates if the session is already taken over by another human. - Updates the session to reflect the current user as the human taking over. - Sends a message to the chat group about the takeover. - Creates a log entry for the takeover asynchronously. """ request = self.request session: Session = self.get_object() # Check if the session is already taken … -
How to use schema with variable to pass though different environnement
I try to variabilise schema name because i use different environnment for my project. So i do this in my models.py: # from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser #Pour plus d'information sur le fonctionnement des models : https://docs.djangoproject.com/fr/5.1/topics/db/models/ from django.conf import settings if settings.ENV == "DEV": schema="applications_db" elif settings.ENV == "VIP": schema="applications_vip_db" elif settings.ENV == "PROD": schema="applications_prod_db" class ApplicationDjango(models.Model): a_name = models.CharField(max_length=100,verbose_name="Nom") a_portail_name = models.CharField(max_length=100,verbose_name="Nom portail") a_views_name = models.CharField(max_length=100,verbose_name="Views name") a_url_home = models.CharField(max_length=100,verbose_name="Url home") def __str__(self): return self.a_name+"_"+self.a_portail_name #class pour ajouter une contrainte d'unicité class Meta: managed= True db_table = f'{schema}.\"ApplicationDjango\"' i make my migration --> noproblem then when i migrate i got this error : ./manage.py migrate Applications Operations to perform: Apply all migrations: Applications Running migrations: Applying Applications.0004_alter_applicationdjango_table_alter_user_table...Traceback (most recent call last): File "/home/webadmin/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.SyntaxError: syntax error at or near "." LINE 1: ...ons_applicationdjango" RENAME TO "applications_db"."Applicat... ^ i try several things but it dont work. I hope that i can variablise schema name :/ Thanks for the help -
How can I send data via copy paste operation in Django Views or model?
I have such a very difficult problem. Which is very specific and not easy to enter data. I am thinking how to send data to the database or, as an option, just send data to the code in the internal Django code for processing in Views. Is it possible, for example, to have the ability to send data not one by one in the singular, to fill in the input field. Fill in the input field not only one in the singular. For example, as the most common case of data processing in office or other applications - the copy / paste operation. So in this frequent popular operation - for example, we want to copy several elements in an Excel table and try to insert them somehow send to the code in the internal Django code for processing in Views. Is it possible to implement something similar? So as not to manually enter data, but somehow have the ability to do this in a semi-automatic form - by copying several cells with data and pasting them into some kind of form or something similar? How can I send data via copy paste operation in Django Views or model? from … -
Suds throwing exception on "type not found"
We are using SUDS v1.1.1 and recently starting getting a "Type not found" exception as the response to a request contains a field not in the wsdl. I tried initializing the client with the strict keyword as follows but the exception is still occurring: client = Client(spec_path, strict=False, faults=False) Is there any other way to get suds to ignore the unknown field without throwing an exception please? -
Django Rest Framework Cursos pagination with multiple ordering fields and filters
I have an issue with DRF, CursorPagination and Filters. I have an endpoint. When I access the initial page of the enpoint I get a next URL "next": "http://my-url/api/my-endpoint/?cursor=bz0yMDA%3D&date__gte=2025-04-25T10%3A00%3A00Z&date__lte=2025-04-26T10%3A00%3A00Z" When I access this URL I get a previous URL "next": "http://my-url/api/my-endpoint/?cursor=bz00MDA%3D&date__gte=2025-04-25T10%3A00%3A00Z&date__lte=2025-04-26T10%3A00%3A00Z", "previous": "http://my-url/api/my-endpoint/?cursor=cj0xJnA9MjAyNS0wNC0yNSsxMCUzQTAwJTNBMDAlMkIwMCUzQTAw&date__gte=2025-04-25T10%3A00%3A00Z&date__lte=2025-04-26T10%3A00%3A00Z", Now when I try to access the previous URL, I get an empty result list. Here is the code for the endpoint class RevenuePagination(CursorPagination): page_size = 200 ordering = ['date', 'custom_channel_name', 'date', 'country_name', 'platform_type_code', 'id'] class RevenueFilter(django_filters.FilterSet): class Meta: model = Revenue fields = { 'date': ['lte', 'gte'], 'custom_channel_name': ['exact'], 'country_name': ['exact'], 'platform_type_code': ['exact'], } class RevenueViewSet(viewsets.ModelViewSet): permission_classes = [HasAPIKey] queryset = Revenue.objects.all() serializer_class = RevenueSerializer filterset_class = RevenueFilter pagination_class = RevenuePagination ordering = ['date', 'custom_channel_name', 'date', 'country_name', 'platform_type_code', 'id'] ordering_fields = ['date', 'custom_channel_name', 'date', 'country_name', 'platform_type_code', 'id'] @revenue_list_schema() def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) From what I get, the problem seems to be that the previous URL cursor (cj0xJnA9MjAyNS0wNC0yNSsxMCUzQTAwJTNBMDAlMkIwMCUzQTAw) gets decoded to r=1&p=2025-04-25+10:00:00+00:00, which is not right, because only the date field is in the cursor, while I have specidied 6 fields in the ordering of the pagination. I tried it narrowing down the order to ['date', 'id'], but it does not work. … -
PYTHON FACIAL RECOGNITION (OPEN CV + FACE_RECOGNITION)
I need some help with a project I'm working on. I currently have a Python script that performs facial recognition using OpenCV and the face_recognition library. The script works fine in standalone Python, but now I need to transform it into a Django web application. My goal is to create a Django-based system where users can register their faces via the web interface, and later use facial recognition for authentication or access control. I'm struggling with how to properly integrate the image capturing, face encoding, and recognition process into Django views and models. Specifically, I'm not sure how to handle: Capturing images from the user's webcam via the web interface. Processing the images with face_recognition in Django views. Storing and retrieving face encodings in the Django database. Handling real-time recognition or verification from the web app. If anyone has experience with this or knows of any good tutorials, examples, or tips, I would greatly appreciate your help. Thank you in advance! -
setup dj_rest_auth and all allauth not working
Hello i'm trying to setup dj_rest_auth and allauth with custom user model for login for my nextjs app but it seems not working the backend part besides it not working i get this warning /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:228: UserWarning: app_settings.USERNAME_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['username']['required'] required=allauth_account_settings.USERNAME_REQUIRED, /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:230: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required'] email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED) /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:288: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required'] email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED) No changes detected # python manage.py migrate /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:228: UserWarning: app_settings.USERNAME_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['username']['required'] required=allauth_account_settings.USERNAME_REQUIRED, /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:230: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required'] email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED) /usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:288: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required'] email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED) versions i use Django==5.2.1 django-cors-headers==4.3.1 djangorestframework==3.16.0 dj-rest-auth==7.0.1 django-allauth==65.8.1 djangorestframework_simplejwt==5.5.0 psycopg2-binary==2.9.10 python-dotenv==1.0.1 Pillow==11.2.1 gunicorn==23.0.0 whitenoise==6.9.0 redis==5.2.1 requests==2.32.3 models.py import uuid from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser, PermissionsMixin, UserManager # Create your models here. class MyUserManager(UserManager): def _create_user(self, name, email, password=None , **extra_fields): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email=email) user = self.model(email=email , name=name, **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_user(self, name=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff',False) extra_fields.setdefault('is_superuser',False) return self._create_user(name=name,email=email,password=password,**extra_fields) def create_superuser(self, name=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self._create_user(name=name,email=email,password=password,**extra_fields) class Users(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = None last_name = … -
Django's manage.py dumpdata adds free text to each file
I am trying to move Django data from SQLite to Postgres, following this flow: SQLite connection in settings.py manage.py dumpdata > data.json Postgres connection in settings.py manage.py loaddata data.json It seems to be sort of working (still struggling with "matching query does not exist" errors), but one thing definitely looks like a bug: The data.json file always starts with a free-text line "Tracking file by folder pattern: migrations". Then follows the JSON content. As the result, the command loaddata gives the to be expected error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) It all works fine if open the JSON file in a text editor and delete that first line. It also makes sense that the line is there, since dumpdata without > data.json outputs "Tracking file by folder pattern: migrations" before the data. Is there a way to prevent Django from writing that line to the file? -
Django ModelFormset_Factory issue with rendering form
I've reviewed other questions and answers, worked through the django documentation and followed tutorials but I can't get my model formset to render correctly. So far, I have the following working fine: forms.py class BulkUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BulkUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = "post" self.helper.layout = Layout( Row( Column("slug"), ), Row( Column("registered"), Column("start_date"), Column("end_date"), Column("achieved"), Column("pfr_start"), Column("pfr_end"), ), ) self.fields["slug"].label = "" class Meta: model = LearnerInstance fields = ["id","slug","registered","start_date","end_date","achieved","pfr_start","pfr_end", ] widgets = { "slug": forms.TextInput( attrs={ "readonly": True, }, ), } template <div class="container d-flex align-items-center flex-column pt-1"> <div class="card text-dark bg-light mb-3 p-3" style="max-width: 95rem;"> <br> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% crispy form %} <hr> {% endfor %} </div> <input type="submit" name='registered', class="btn btn-primary" value="Update"> </form> </div> views.py def bulk_update(request): context = {} selected_rows = request.POST.getlist("select") #posted from previous page with a table and checkboxes to select the queryset I need to update BulkFormset = modelformset_factory( LearnerInstance, form=BulkUpdateForm, edit_only=True, extra=0) queryset = LearnerInstance.objects.filter(id__in=selected_rows) formset = BulkFormset(queryset=queryset) context["formset"] = formset return render(request, "learner/bulk_update.html", context) Results in the following output, which is what I hope to see: However - when I add request POST BulkFormset … -
Debugging django admin 403 Forbidden error
I am trying to access django admin with my credentials. No matter whether the credentials are correct or not I just keep geeting 403 forbidden with the reason "CSRF cookie not set". Using chrome dev tools I can clearly see the CSRF cookie in the network tab under response headers. Does anyone know how to fix this and regain access to django admin??? -
Django admin drop down based on object open
I would like to use admin to do a lot of the heavy lifting in an application im building. I require the field icon in admin_navigation to be filtered by business that is in view. for example: icon.objects.filter(business = self.business.id) class admin_navigation(admin.TabularInline): list_display = [field.name for field in navigation._meta.fields] readonly_fields = [] verbose_name = "Navigation" verbose_name_plural = "Navigations" model = navigation extra = 0 can_delete = True classes = ['collapse'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "icon": if request.method == 'GET': bus_id = self.business.id #<----- here is my issue kwargs["queryset"] = icon.objects.filter(business = bus_id) return super(admin_navigation, self).formfield_for_foreignkey(db_field, request, **kwargs) class admin_icon(admin.TabularInline): list_display = [field.name for field in icon._meta.fields] readonly_fields = ['icon_display'] verbose_name = "Icon" verbose_name_plural = "Icons" model = icon extra = 0 can_delete = True classes = ['collapse'] @mark_safe def icon_display(self, obj): return f'<script src="/static/falcon/vendors/fontawesome/all.min.js"></script><span class="{obj.class_name}"/>' class admin_business(admin.ModelAdmin): list_display = [field.name for field in business._meta.fields] inlines = [admin_icon, admin_navigation] admin.site.register(business, admin_business) -
Django: dependencies reference nonexistent parent node creating a custom user
I am learning Django this is just a personal and local project. In the middle of development I decided to change my user to a CustomUser that I created with AbstractUser. When typing python manage.py makemigrate I got this error: Traceback (most recent call last): File "/Users/pauleera/Documents/Diplomado /Ejemplos Python/Django/projects/pettry save money/pettry_project/manage.py", line 22, in <module> main() File "/Users/pauleera/Documents/Diplomado /Ejemplos Python/Django/projects/pettry save money/pettry_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/base.py", line 416, in run_from_argv self.execute(*args, **cmd_options) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/base.py", line 107, in wrapper res = handle_func(*args, **kwargs) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 140, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/db/migrations/loader.py", line 276, in build_graph self.graph.validate_consistency() File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/db/migrations/graph.py", line 198, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/db/migrations/graph.py", line 198, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/pauleera/miniconda3/envs/work/lib/python3.10/site-packages/django/db/migrations/graph.py", line 60, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_user_favorites dependencies reference nonexistent parent node ('products', '0002_alter_productprice_price_favoriteproduct') ** I have already deleted migrations files, also the db.sqlite3 file** Can you help me to solve it? I … -
Company with many different names
I have the following situation that looks simple, but I do not know how to make models for it :( Here is what I have. Model Company that contains only description (field note) class Company(models.Model): note = models.TextField(_('note'), blank=True, null=True) class Meta: verbose_name = _('Company') def __str__(self): return f'{self.id}' Each company can have many different names (Official Name, Short Name, Long Name, etc.) I have model CompanyName for it. class CompanyName(models.Model): company = models.ForeignKey(Company, related_name='name_set') type = models.CharField(_('type'), max_length=4, choices=NameType.choices) name = models.CharField(_('name'), max_length=256) class Meta: verbose_name = _('Company name') def __str__(self): return f'{self.type} {self.name}' The issue I have: How inside Company model get 'Official Name' from CompanyName Model. I would like to use the official name instead of f'{self.id}' inside __str__ function. Thank you so much for your help and time, -
Django and IIS, handlers not functioning as expected
I have been working on developing an internal website for my company, I am using django as the framework. Once I went through the process of moving everything to IIS I lose my css files for the admin page. I have tried swapping the handlers from django fastcgi being first and staticfilehandler being first, if django is first then everything loads and works except for the admin page issue, but if static is first then everything breaks. I have edited the applicationHost.config file to allow overrides and changed the definitions as well. -
How can I connect multiple model tables Django for data import export?
I have three 3 Django model tables. They are kind of connected to each other so that each row, each line from one model table corresponds to the same from another model table. You could say that I'm just splitting one large model table into three 3 medium small ones. And each row, line from one model table is equal to belongs to another. Rows, rows from 3 tables - one row from 3 tables - these are the parameters of one object. How can I somehow connect these three 3 model tables? I'll be glad to any help. I want to save and upload data simultaneously to 3 model tables through the form. How can I somehow load and receive data. How can I connect multiple model tables for data import export? How can I connect multiple model tables for data import export as if it were one large model table - merged from 3 model tables? from django.db import models class Musician_1(models.Model): first_name_1 = models.CharField(max_length=50) last_name_1 = models.CharField(max_length=50) instrument_1 = models.CharField(max_length=100) class Musician_2(models.Model): first_name_2 = models.CharField(max_length=50) last_name_2 = models.CharField(max_length=50) instrument_2 = models.CharField(max_length=100) class Musician_3(models.Model): first_name_3 = models.CharField(max_length=50) last_name_3 = models.CharField(max_length=50) instrument_3 = models.CharField(max_length=100) -
python manage.py tailwind install seems to run in wrong directory
I installed Django-tailwind according to the documentation but am now facing an issue when trying to python manage.py tailwind install. The theme app was created successfully and contains a package.json file. npm is found since i specified the NPM_BIN_PATH. However, on running the install command i get an ENOENT error no such file or directory, open 'C:\Windows\package.json The Package is on \[...]\project\theme\static_src\package.json It seems that node is looking for the package outside of the project directory. What do I have to change for the script to reference my project DIR? VS Code is executed as admin and the terminal is in the project directory. I am on Windows 11 Home version 24H2, node v22.16.0 and npm 10.9.2 The error message: npm error code ENOENT npm error syscall open npm error path C:\Windows\package.json npm error errno -4058 npm error enoent Could not read package.json: Error: ENOENT: no such file or directory, open 'C:\Windows\package.json' npm error enoent This is related to npm not being able to find a file. -
How to send real emails via Gmail SMTP in Cookiecutter Django project?
I'm using Cookiecutter Django for my project, and I’d like to start sending real emails through Gmail SMTP (not just to Mailpit) — for example, welcome emails after user registration. Right now, in local.py, email is configured like this: EMAIL_HOST = env("EMAIL_HOST", default="mailpit") EMAIL_PORT = 1025 This works fine for local testing — emails show up in Mailpit at localhost:8025. But now I want to send real emails to users via Gmail when running in production (or even temporarily in development for testing real delivery). I already have Gmail App Passwords set up and my .envs/.production/.django file contains: EMAIL_HOST_USER=something@gmail.com EMAIL_HOST_PASSWORD=my-app-password DEFAULT_FROM_EMAIL=something@gmail.com And in production.py, I have: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL") My questions: Is this the correct way to send real emails using Gmail SMTP in Cookiecutter Django? Is there anything else I need to do to make this work in production? Can I test Gmail sending locally without breaking the Cookiecutter setup? Thanks in advance! -
Okta Redirection based on attribute then access SubPage
I have a successfully authenticated and got redirected to my role let's say Admin page, in my Okta it is called http://test.com/myAdmin I have other redirects depending on the users roles; however, that those work as well and their URI are: http://test.com/myOtherRole1 http://test.com/myOtherRole2 I am perplexed because when I go to access let's say from my Django routes from urls.py: url_patterns=[ ..., path("myAdmin/", views.Adminrole, name="Admin_Home"), path("myAdmin/mainpanel", views.mainpanel, name="view"), ] I cannot do so after Okta sign-in and landing on http://test.com/myAdmin. So the next page I should be able to access is: http://test.com/myAdmin/mainpanel I am expecting to access each subdomain in each route in urls.py. Does that mean I have to include them in Okta Redirect URI? Because I keep getting an error 403 when I try to advance to other pages. -
Problems with Django admin model page. Slow performance
I have a problem with a change view of an model in Django. I have profiled the endpoint with different tools, and also took logs of the database queries run using shell plus. I can't see any long calls on the pg db and the cprofiler tool i used shows no long calls in the stack trace , but the response takes longer than 3 mins and i can't find a way to debug it. I also inspected Django source code ModelAdmin and changeform_view it seems to not have slow performance issues there it returns immediately . Any help ? -
DigitalOcean App Platform does not parse ${db.DATABASE_URL} after bulk editor changes
I am using DigitalOcean App Platform to deploy a Django app. The initial deployment worked fine, but I've attempted to use the bulk editor on the component-level environment variables, and since then, the deployment fails when executing dj_database_url.config(default=config('DATABASE_URL'). For debugging, I added this line to settings.py: print(f"[BUILD DEBUG] DATABASE_URL = {repr(os.environ.get('DATABASE_URL'))}") This returns [BUILD DEBUG] DATABASE_URL = '${db.DATABASE_URL}' in the build logs. I don't understand why the environment variable is not resolving. My app spec looks like this: services: - environment_slug: python envs: - key: DATABASE_URL scope: RUN_AND_BUILD_TIME value: ${db.DATABASE_URL} Could this be a bug, or am I doing something wrong? Yes, my database is named correctly: databases: - engine: PG name: db The only thing that changed between my last deployment and this failed deployment, besides a few lines of code, is that I used the bulk editor to add new environment variables. Some of the existing environment variables were encrypted, but they look OK in the app spec. -
Passing Arguments to Django Views From a Rendered Page
I've been tasked to build web-based front end to an existing MySQL database. I'm new to web development in general, decided to use Django because I'm a pretty advanced Python user. However, I'm completely stuck doing what seems like it should be a pretty common task. The database holds information about Software Bill of Materials (SBOMs) and the pieces of software associated with each. Right now, all I want to do is have the user select an SBOM from the database, retrieve the software associated with that SBOM, and display the results. I would like the user to be able to page through the results. I'm trying to do this by rendering a list of SBOMs in the system in HTML, with each entry having an associated button that will pass the selected parameters to the next view in line. As far as I can tell, I have things set up so Here's how my urls.py is set up: urlpatterns = [ path("", views.select_bill, name="select_bill"), path("select_software/<int:bill_num>", views.select_software, name="select_software"), path("select_software/<int:bill_num>/<int:page>", views.select_software, name="select_software") ] my views.py: from django.shortcuts import render from django.core.paginator import Paginator from frontend.models import SoftwareResults RESULTS_PER_PAGE = 25 def select_bill(request): bills = get_bills() # Function that queries the existing … -
Django annotate with ExtractMonth and ExtractYear doesnt extract year
I have this model: class KeyAccessLog(models.Model): key = models.ForeignKey( Key, related_name="access_logs", on_delete=models.CASCADE ) path = models.CharField(max_length=255) method = models.CharField(max_length=10) ip_address = models.GenericIPAddressField() created = models.DateTimeField(auto_add_now=True) class Meta: verbose_name = "Key Access Log" verbose_name_plural = "Key Access Logs" ordering = ("-pk",) indexes = [ models.Index( models.Index( "key", ExtractMonth("created"), ExtractYear("created"), name="key_month_year_idx", ), ), ] def __str__(self): return f"{self.key} - {self.path} - {self.method}" My point is to use the declared index when filtering by key, month, and year but the query that is generated from ORM is not extracting as it does for the month. dt_now = timezone.now() qs = api_key.access_logs.filter(created__month=dt_now.month, created__year=dt_now.year) print(qs.query) gives me: SELECT "public_apikeyaccesslog"."id", "public_apikeyaccesslog"."api_key_id", "public_apikeyaccesslog"."path", "public_apikeyaccesslog"."method", "public_apikeyaccesslog"."ip_address", "public_apikeyaccesslog"."created" FROM "public_apikeyaccesslog" WHERE ( "public_apikeyaccesslog"."api_key_id" = 1 AND EXTRACT( MONTH FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) = 5 AND "public_apikeyaccesslog"."created" BETWEEN '2025-01-01 00:00:00+00:00' AND '2025-12-31 23:59:59.999999+00:00' ) ORDER BY "public_apikeyaccesslog"."id" DESC Now I tried explicitly to annotate extracted month and year: dt_now = timezone.now() qs = api_key.access_logs.annotate( month=ExtractMonth("created"), year=ExtractYear("created") ).filter(month=dt_now.month, year=dt_now.year) print(qs.query) this gives me almost the same SQL: SELECT "public_apikeyaccesslog"."id", "public_apikeyaccesslog"."api_key_id", "public_apikeyaccesslog"."path", "public_apikeyaccesslog"."method", "public_apikeyaccesslog"."ip_address", "public_apikeyaccesslog"."created", EXTRACT( MONTH FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) AS "month", EXTRACT( YEAR FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) AS "year" FROM "public_apikeyaccesslog" … -
Custom id generation on bulk_create in django
I want different models in my django project to have different prefixes (like usr_ for user, acc_ for account etc.) I then want to append a nanoid to this prefix. I defined a basemodel which is used by all the other models and I overrode the basemodel's save method to create the id in the format I want. But the issue is that when I use bulk_create the ids are not in the format I want. What is the easiest way that I can generate my custom ids in bulk_create that can be used by all other models. -
How can I link multiple Django model tables as if they were one when entering data?
Good morning! I am a bit new to Django. I wanted to ask about the relationships between Django model tables. I have several Django model tables. They should all belong to the same correspondence - a row from one table - is respectively related to a row from another table. That a row from one model table is also and, respectively, a row from another model table - they belong to and characterize one object. This is how I split one large table into several. How can I make the tables related and - so that when filling in only one form through the Django model form - other related tables are also automatically filled in. How can I form a single QuerySet or DataFrame from these several respectively related model tables. How can I automatically send data not only to one table but also to others when sending data from the Django model form, which are related to several Django model tables as if they were one when entering data? How can I link multiple Django model tables as if they were one when entering data? class MyModel(models.Model): id = models.AutoField(primary_key=True) # Auto-incrementing integer uuid = models.UUIDField(default=uuid.uuid4) name = … -
Could not find backend 'storages.backends.s3boto3.S3StaticStorage'
When deploying my Django app it just (seems like) stopped to connect to my S3 bucket. The full message I get when running collectstatic is Traceback (most recent call last): File "/home/ubuntu/campmanager/manage.py", line 22, in <module> main() File "/home/ubuntu/campmanager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 416, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 184, in handle if self.is_local_storage() and self.storage.location: File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 245, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/utils/functional.py", line 280, in __getattribute__ value = super().__getattribute__(name) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/utils/functional.py", line 251, in inner self._setup() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", line 542, in _setup self._wrapped = storages[STATICFILES_STORAGE_ALIAS] File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/files/storage/handler.py", line 34, in __getitem__ storage = self.create_storage(params) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/files/storage/handler.py", line 45, in create_storage raise InvalidStorageError(f"Could not find backend {backend!r}: {e}") from e django.core.files.storage.handler.InvalidStorageError: Could not find backend 'storages.backends.s3boto3.S3StaticStorage': Module "storages.backends.s3boto3" does not define a "S3StaticStorage" attribute/class This is my setting in settings.py STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = 'static/' AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA_LOCATION = 'media-dev' MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA_LOCATION) …