Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reduce latency in translating the speech to text (real time) in a Django-React project?
I have implemented a speech to text translation in my django-react project. I am capturing the audio using the Web Audio API, ie, using navigator.mediaDevices.getUserMedia to access the microphone, AudioContext to create a processing pipeline, MediaStreamAudioSourceNode to input the audio stream, AudioWorkletNode to process chunks into Float32Array data, and AnalyserNode for VAD-based segmentation.processes it into 16-bit PCM-compatible segments, and streams it to the Django backend via web socket. The backend, implemented in consumers.py as an AudioConsumer (an AsyncWebsocketConsumer), receives audio segments or batches from the frontend via WebSocket, intelligently queues them using a ServerSideQueueManager for immediate or batched processing based on duration and energy, and processes them using the Gemini API (Gemini-2.0-flash-001) for transcription and translation into English. Audio data is converted to WAV format, sent to the Gemini API for processing, and the resulting transcription/translation is broadcast to connected clients in the Zoom meeting room group. The system optimizes performance with configurable batching (e.g., max batch size of 3, 3-second wait time) and handles errors with retries and logging. Now there is a latency in displaying the translated text in the frontend. There is an intial delay of 10s inorder to display the first translated text. Subsequent text will … -
How to change the breakpoint at which changelist table becomes stacked?
In Unfold admin, the changelist table switches to a stacked layout on small screens — likely due to Tailwind classes like block and lg:table. I’d like to change the breakpoint at which this layout switch happens (for example, use md instead of lg, or disable it entirely to keep horizontal scrolling). How can this behavior be customized or overridden cleanly? -
How to find and join active Django communities for learning and collaboration?
How can I actively engage with the Django community? Looking for forums, Discord/Slack groups, or events to discuss best practices, ask questions, and contribute. Any recommendations? I want to connect with the Django community for learning and collaboration. I checked the official Django forum but couldn't find active discussions. What I tried: Searching Meetup.com for local Django groups (none in my area) Browsing Reddit's r/django (mostly news, not interactive) What I expect: Active Discord/Slack channels for real time help Local study groups or hackathons Contribution opportunities for beginners Any recommendations beyond official docs? -
How to use login_not_required with class-based views
Django 5.1 introduced the LoginRequiredMiddleware. This comes with the companion decorator login_not_required() for function-based views that don't need authentication. What do I do for a class-based view that doesn't need authentication? -
Django SSL error during send_mail() while explicitly using TLS
I'm trying to perform a send_mail() call in my Django application, but the mails are not sending. Checking the logs, I see the following error: [Thu May 29 09:35:20.097725 2025] [wsgi:error] [pid 793757:tid 140153008285440] [remote {ip.ad.dr.ess}:65062] Error sending email: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1147) My smtp relay uses TLS w/ whitelisting, not SSL, and I've reflected that in my /project/settings/base.py file by setting EMAIL_USE_TLS = True. I've checked my certificate and it's up-to-date and my website's HTTPS is functional. I don't understand where the disconnect lies - why could an SSL error be preventing my email from sending when I'm using TLS? -
Django manage.py Command KeyboardInterrupt cleanup code execution
do you have an idea how to use signals in custom management commands in Django? My Command's handle method processes continious stuff which needs to be cleaned up, when Command is interrupted. Without any specific additional signal handling, my Command class could look like this: class Command(BaseCommand): def handle(self, *args, **kwargs): while True: print("do continuous stuff") time.sleep(1) def cleanup(self, *args, **kwargs): print("do cleanup after continuous stuff is interrupted") Does not work out, because signal is already caught by django: def handle(self, *args, **kwargs): try: while True: print("do continuous stuff") time.sleep(1) except KeyboardInterrupt as e: self.cleanup() raise e Does not work out, because signal is not passed here: def handle(self, *args, **kwargs): self.is_interrupted = False signal.signal(signal.SIGINT, self.cleanup) while not self.is_interrupted: print("do continuous stuff") time.sleep(1) def cleanup(self, *args, **kwargs): self.is_interrupted = True print("do cleanup after continuous stuff is interrupted") raise KeyboardInter Do you have an idea? -
Working in django with data with a saved history of changes
I am creating an information system in which some entities have separate attributes or a set of them, for which it is necessary to store a history of changes with reference to the date of their relevance for further processing in conjunction with other entities. In particular, I have main entity Customer and one or a related set of date-related attributes (for example, the official names of Customer), which may change over time. What is the best or possible way to implement the interaction of the model for main entity, but with their history must be preserved? Here’s what I’ve come up with so far. The class code is probably redundant, but this is done specifically to demonstrate the problem. Main class: class Customer(models.Model): name = models.CharField(max_length=128, verbose_name='Customer system name') # A key for relation with current value of secondary class # I have doubts about the correctness of adding this field, # but so far I have not come up with anything better. legal_names = models.ForeignKey('CustomerNames', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Legal customer names') Auxiliary (secondary) class: class CustomerNames(models.Model): # A key for relation with the main model, specifying a list of names customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_names', verbose_name='Customer') short_name = … -
Why postgres service if If you buy a managed PostgreSQL database from DigitalOcean?
Why do we need to add postgres service if we buy postgress database on DigitalOcean ? For me there is two ways to setup our database : Solution 1 : Let docker handle it by taking advantage of docker network. We configure Docker then to run PostgreSQL as a service. For this solution, no need to buy DigitalOcean database since we can map with volumes (./data/db:/var/lib/postgresql/data). Data persisted with volumes then Solution 2 : Buy DigitalOcean database. For this solution no need to setup postgress service with docker. PostgreSQL runs on DigitalOcean's infrastructure. We take advantages of DigitalOcean. DigitalOcean handles maintenance, backups, security, ... in this case. So for me, No PostgreSQL Docker service needed. So I am in this django project and despite the fact that we have our PostgreSQL runs on DigitalOcean's infrastructure in the docker-compose we steel have postgres service. So my question is why then do we need postgress service if we decide to take DigitalOcean database offer ? why do we need postgress service in this case for docker ? Just wanna understand. My crew gave me some explanations but do not understand very well. So can anyone help me to understood ? -
How to handle unfamiliar real-time tasks in Django projects without proper documentation?
We’re working with backend developers who frequently encounter real-time tasks that fall outside their core experience—for example, integrating Django applications with older third-party systems (e.g., SOAP-based services, custom XML APIs) or poorly documented internal tools. A common issue involves connecting to a SOAP API using zeep, and getting stuck handling WSSE or custom header authentication. The developers often find minimal guidance in the official docs, and very few examples online. In situations like this, where tasks are time-sensitive and documentation is lacking, what’s an effective way to: Break down the problem Debug effectively Find reliable patterns or tools to apply We’re looking to understand how experienced Django or backend developers approach unknowns like this under time pressure. I used the zeep library in Django to connect with a SOAP API. I followed the official docs and tried loading the WSDL and passing headers via the client. I expected a successful response from the server, but instead, I’m getting authentication or connection errors. I’ve tried different header formats and debug logs but can’t figure out what’s wrong. Looking for better ways to handle such situations. -
ModelViewSet does not overwrite DEFAULT_PERMISSION_CLASSES'
Hello I'm working on making all urls requires user to be authenticate , but some urls i want them to be accessible by public, so i use permission_classes = [AllowAny] and authentication_classes = ([]) to overwrite default configurations it work in APIVIEW but not in viewsets.ModelViewSet why ? settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_FILTER_BACKENDS': [ 'django_filters.rest_framework.DjangoFilterBackend', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S", } views.py class ToolsListViewSet(viewsets.ModelViewSet): serializer_class = ToolsListSerializer permission_classes = [AllowAny] authentication_classes = ([]) pagination_class = None def get_queryset(self): return Tools.objects.filter(is_active=True) enter code here error { "detail": "Authentication credentials were not provided." } -
How can I organize the structure of entering the city/restaurant tables of the Django database?
Good day! I have a plan for the database structure. An example is in the figure below. For example, I have - all coffee shops - within one region - state or several regions. In one city there are several cafes. In total, there can be 200 cafes and 10 cities. The problem is how to enter data on cafes in the database tables. And also change them if necessary. Enter data through forms. Each cafe also has the following parameters - address, Internet page, profitability, income, number of staff, i.e. data belonging to one cafe. As well as staff and menu. I think to first enter the cities in which there will be cafes. And then enter the names of the cafes. And even later other parameters through other forms. How can I make it so that at the second stage only the name, address is entered and then successively filled with other data? How can I organize the structure of entering the city / restaurant tables of the Django database? from django.db import models # Create your models here. class CityCafe (models.Model): city = models.CharField(verbose_name="City") class ObjectCafe (models.Model): name = models.TextField(verbose_name="Cafe Name") name_city = models.ForeignKey(CityCafe) class BaseParametrCafe (models.Model): … -
Update LANGUAGE_CODE in Wagtail before internationalization?
I've developed a site in Wagtail, but missed to update the LANGUAGE_CODE before the first (and several other) migrations. In the Internationalization instructions the following is noted: "If you have changed the LANGUAGE_CODE setting since updating to Wagtail 2.11, you will need to manually update the record in the Locale model too before enabling internationalization, as your existing content will be assigned to the old code." But, how do I manually update the the record in the Locale model? -
Low RPS when perfomance testings django website
I have a code like this that caches a page for 60 minutes: import os import time from django.conf import settings from django.core.cache import cache from django.core.mail import send_mail from django.contrib import messages from django.http import FileResponse, Http404, HttpResponse from django.shortcuts import render from django.utils.translation import get_language, gettext as _ from apps.newProduct.models import Product, Variants, Category from apps.vendor.models import UserWishList, Vendor from apps.ordering.models import ShopCart from apps.blog.models import Post from apps.cart.cart import Cart # Cache timeout for common data CACHE_TIMEOUT_COMMON = 900 # 15 minutes def cache_anonymous_page(timeout=CACHE_TIMEOUT_COMMON): from functools import wraps from django.utils.cache import _generate_cache_header_key def decorator(view): @wraps(view) def wrapper(request, *args, **kw): if request.user.is_authenticated: return view(request, *args, **kw) lang = get_language() # i18n curr = request.session.get('currency', '') country = request.session.get('country', '') cache_key = f"{view.__module__}.{view.__name__}:{lang}:{curr}:{country}" resp = cache.get(cache_key) if resp is not None: return HttpResponse(resp) response = view(request, *args, **kw) if response.status_code == 200: cache.set(cache_key, response.content, timeout) return response return wrapper return decorator def get_cached_products(cache_key, queryset, timeout=CACHE_TIMEOUT_COMMON): lang = get_language() full_key = f"{cache_key}:{lang}" data = cache.get(full_key) if data is None: data = list(queryset) cache.set(full_key, data, timeout) return data def get_cached_product_variants(product_list, cache_key='product_variants', timeout=CACHE_TIMEOUT_COMMON): lang = get_language() full_key = f"{cache_key}:{lang}" data = cache.get(full_key) if data is None: data = [] for product in … -
Django Admin site css not loading so site is lokking broken
I am using django's admin site and in that css is not loadung so site is looking totally broken.In last 3-4 days i almost tried everything which is available around the web to fix it but its not getting fixed. As this is my new account i am not able to post the images. If anyone have any idea to solve this issue then please tell me!! from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure--yt4su$h2u!*nnnl=)_)7@0(z!63t2jvf#zb@+3sa^cc-514)!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sample.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sample.wsgi.application' # Database # https://docs.djangoproject.com/en/5.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators … -
Problems integrating Django and Tableau with Web Data Connector (WDC)
I’m working on a project where I need to integrate data from my Django application into Tableau using a Web Data Connector (WDC). However, I’m running into several issues and would appreciate any help or guidance from the community. Setup: Backend: Django (Python) Goal: Tableau Dashboard Connection: Web Data Connector (WDC) What I’ve done so far: I created a WDC that fetches data from my Django API. The API provides JSON data, which I want to pass to Tableau via the WDC. The WDC was built using JavaScript and connects to the Django API. Issues: CORS Errors: Tableau seems to have issues with the Cross-Origin Resource Sharing (CORS) settings in my Django application. I’ve installed and configured django-cors-headers, but the error persists. Slow Data Transfer: When dealing with large datasets, the transfer from Django to Tableau is extremely slow. Authentication: My Django API uses token-based authentication, but I’m unsure how to implement this securely in the WDC. My Questions: How can I resolve CORS issues between Django and Tableau? Are there best practices to speed up data transfer between Django and Tableau? How can I securely implement authentication (e.g., token-based or OAuth) in the WDC for Django? Additional Information: Django … -
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???