Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
password rest email notification or just email notification
I have a project in DJANGO and in the settings GEMENI is persitant on hard codeing my email and i dont want it hard coded for a password reset i want it to read from the .db file and be able to use multy emails not just gmail attached will be the settings.py file and gemini is consitant on keeping the setting file like this and im at a lose on this any help would be great it is a great project that users can apply for almost anything the model based is project tracker enter image description here -
How to migrate Django from local sqlite3 to postgresql Docker container?
I'm trying to learn Django with some demo projects and want to migrate from sqlite3 to a local postgresql container for dev work. When I try to run uv run python manage.py migrate, I get the following exception: django.db.utils.OperationalError: connection failed: connection to server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "myuser" While the container is running, the database is accessible via psql, and my pg_hba.conf looks like it should be allowing authentication: # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust host all all all scram-sha-256 I'm creating and running my postgresql container with: docker run --name=db_container -d -e POSTGRES_DB=mydatabase -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword -p 5432:5432 postgres:16.2 My .env file contains: POSTGRES_DB=mydatabase POSTGRES_USER=myuser POSTGRES_PASSWORD=mypassword HOST=localhost PORT=5432 My settings.py file contains: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('POSTGRES_DB'), 'USER': config('POSTGRES_USER'), 'PASSWORD': config('POSTGRES_PASSWORD'), 'HOST': config('HOST'), 'PORT': config('PORT'), } } … -
What is the correct way of using Django's get_context_data() method to add key-value pairs to a context?
How can Django's get_context_data() method be used to add new key-value pairs to a context in the views.py file? I am following along with a tutorial and thus far everything has worked well, however at the moment I can't get the added context entries to populate the html template. Here's what I've got thus far, based on the instructions in the tutorial: views.py: from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class AboutPageView(TemplateView): template_name = "about.html" def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context["contact_address"] = "123 Jones Street" context["phone_number"] = "01234 678910" return context about.html (the template): <h1>Company About Page</h1> <p>The company address is {{contact_address}}.</p> <p>The company phone number is {{phone_number}}.</p> urls.py: from django.urls import path from .views import home_page_view, AboutPageView urlpatterns = [ path("about/", AboutPageView.as_view()), path("", home_page_view) ] This results in an output which doesn't drag through the values associated contact_address and phone_number to the website when I run the dev server: What I am doing wrong? I've double-checked the sample code several times, and can't see that I'm mis-typing anything. I've also browsed for solutions online but many of the responses seem to relate to scenarios that are a bit far ahead … -
Problems in React axios request to Django backend ( rest framework ) , Error 404 Not Found
I have created a backend with Django so that a user can subscribe to services provided by other users. If I add the user to another user's service list from Thunder, the request succeeds and the user is added, but if I try to do it from my react app it returns the error. AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 400" name : "AxiosError" request : XMLHttpRequest onabort : ƒ handleAbort() onerror : ƒ handleError() onload : null onloadend : ƒ onloadend() onloadstart : null onprogress : null onreadystatechange : null ontimeout : ƒ handleTimeout() readyState : 4 response : "{"affiliations":["Expected a list of items but got type \"int\"."]}" responseText : "{"affiliations":["Expected a list of items but got type \"int\"."]}" responseType : "" responseURL : "http://127.0.0.1:8000/api/listofmembers/create/" responseXML : null status : 400 statusText : "Bad Request" timeout : 0 upload : XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …} withCredentials : false [[Prototype]] : XMLHttpRequest response : {data: {…}, status: 400, statusText: … -
django - saving image to Supabase bucket, but image is blank
I'm uploading image through Angular - django - Supabase s3. To send image to Supabase bucket im using django-storages module. When i get image from supabase image gets corrupted with additional bytes. Here is my settings of django-storages STORAGES = { "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": os.getenv('SUPABASE_STORAGE_BUCKET_NAME'), "region_name": os.getenv('SUPABASE_S3_REGION_NAME'), "access_key": os.getenv('SUPABASE_S3_ACCESS_KEY_ID'), "secret_key": os.getenv('SUPABASE_S3_SECRET_ACCESS_KEY'), "endpoint_url": os.getenv('SUPABASE_S3_ENDPOINT_URL') }, } } Here is my django code of image upload method of Viewset. @action(detail=True, methods=['post'], url_path='image', parser_classes=[FormParser, MultiPartParser]) def image_upload(self, request, pk=None): project = self.get_object() image = request.FILES['image'] project.image = image project.save() projectReadSerializer = ProjectReadSerializer(project) return Response(data = projectReadSerializer.data) whenever I post the image, I get blank image from the supabase bucket, which has more bytes than the original. Any solutions? I've tried to download the image, here is the result: original and bucket image I've also checked the image using PIL and it seemed fine: def image_upload(self, request, pk=None): project = self.get_object() image = request.FILES['image'] img = Image.open(image) img.show() project.image = image project.save() projectReadSerializer = ProjectReadSerializer(project) return Response(data = projectReadSerializer.data) so the problem is in project.image = image part of code, as it seems. -
ImportError for venv/lib64/python3.9/site-packages/oracledb/base_impl.cpython-39-x86_64-linux-gnu.so
I have a Django app that runs fine under runsslserver, but when I run it under Apache, the traffic gets to the app, but 'import oracledb' fails. I was using cx_Oracle previously (which also threw an ImportError) and switiched to oracledb hoping that would solve the problem. I tried compiling the mod_wsgi.so (5.0.2), but again I get the same error. Any suggestions? This is on RHEL 9, python 3.9 -
Why some staticfiles of Django wont add
I try to load all files from static folder that is located in root of my project. Some of them load successfuly, but some of them wont My folders: My_Project | -- static | -- folder that load successfuly \ -- javascripts folder that wont load I tried clearing web cache by pressing Ctrl+Shift+R and clearing it in browser settings, tried to restart my django server, tried to collect staticfiles Few of my settings that i've seen in other problems with static: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'RecruitHelper', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'RecruitHelper/templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] -
Set wrong default value in Django model
So I added a new TimeField to my django model. When I did "python3 manage.py makemigrations" it asked me to choose two options, set a default value now or add one another way. I chose to set one now. I wasn't thinking and set it to "" which is incorrect format for a time field. I have tried everything, even manually in sqlite, removing the new field and more, but I still get an error when running "python3 manage.py migrate" which is saying this: django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format.'] If someone can help. me, it will be gladly appreciated! -
How can I prevent HistoricalModel Creation When Inheriting from Abstract Model?
I have an abstract base model, CompanyAwareModel, which includes historical tracking using TenantHistoricalRecords: class CompanyAwareModel(RequestChangeReasonModelMixin, TenantModel, TimeStampedModel, metaclass=CompanyAwareMeta): tenant_id = 'company_id' company = models.ForeignKey(Company, on_delete=models.CASCADE) history = TenantHistoricalRecords(inherit=True) class Meta: abstract = True To create a variant of this model without historical tracking, I defined another abstract model: class NoHistoryCompanyAwareModel(CompanyAwareModel): history = None class Meta: abstract = True Then, I define a concrete model inheriting from NoHistoryCompanyAwareModel: class Counter(NoHistoryCompanyAwareModel): ... However, when I run makemigrations, Django still creates a HistoricalCounter model, even though I explicitly set history = None in NoHistoryCompanyAwareModel. Interestingly, if I define NoHistoryCompanyAwareModel without inheriting from CompanyAwareModel, like this: class NoHistoryCompanyAwareModel(RequestChangeReasonModelMixin, TenantModel, TimeStampedModel, metaclass=CompanyAwareMeta): tenant_id = 'company_id' company = models.ForeignKey(Company, on_delete=models.CASCADE) history = None class Meta: abstract = True Then makemigrations does not create a historical table for Counter. Question Why does inheriting from CompanyAwareModel still create a historical table, even when history = None is explicitly set? And how can I ensure that Counter does not have a HistoricalCounter model while still inheriting from CompanyAwareModel? I expect that when I inherit the NoHistoryComapnyAwareModel from the CompanyAawreModel and set the history to None it won't create a historicalCounter for my model. -
Requiring 2FA (MFA) with Wagtail private pages. I think this works
This is one of those many times where I think I have a solution but I don't know if I'm doing something problematic I have a Wagtail site where I'm using 2FA sent by email and I have private articles that people have to log in to see Before the fix, when people logged in to the admin panel, everything worked as expected - they were required to enter a code that was emailed to them. But when people logged in to view a private article, they were able to log in without 2FA and once logged in, they could then browse to the admin panel without further challenges I think I fixed this by adding the following line to my url patterns: path("_util/login/", RedirectView.as_view(url="/accounts/login/?next=/accounts")), This works because when someone clicked on an article, they were redirected to _util/login, so the fix was re-redirecting that URL to allauth accounts just like admin/login is redirected This line follows the similar redirect for admin/login so my urls look like: urlpatterns = [ path("django-admin/", admin.site.urls), path("admin/login/", RedirectView.as_view(url="/accounts/login/?next=admin")), path("_util/login/", RedirectView.as_view(url="/accounts/login/?next=/accounts")), path("admin/", include(wagtailadmin_urls)), path("accounts/", include("allauth.urls")), path("documents/", include(wagtaildocs_urls)), path("search/", search_views.search, name="search"), ] But there are two things I'm asking about. First, I don't know how to … -
Django Allauth translation issue: Custom language files not being applied
I'm using Django Allauth and have set up i18n (internationalization) with Spanish (es), English (en), and French (fr) in my Django project. However, I'm experiencing a problem with translations: ✅ English (en) works fine and applies my custom translations. ❌ Spanish (es) is still showing Django Allauth's default translations, even after modifying my locale files. ❌ Even after compiling the translations, my custom django.po files are ignored for Spanish. file: locale/es/LC_MESSAGES/django.po #: templates/allauth/layouts/base.html:49 templates/base.html:124 msgid "Two-Factor Authentication" msgstr "MFA ES" file: locale/en/LC_MESSAGES/django.po #: templates/allauth/layouts/base.html:50 templates/base.html:124 msgid "Two-Factor Authentication" msgstr "MFA EN" Then we run django-admin compilemessages When we switch language every translation works fine but the allauth ones, English works ok (shows MFA EN), but Spanish takes the default ones (Autenticació de doble factor), not the customized form the file (MFA ES). -
WebSocket Streaming Not Working in Django + Next.js — Only Getting First and Final Message
I'm building a ai chat app with Django (Channels) for the backend and Next.js for the frontend. The goal is to stream AI-generated responses chunk by chunk over a WebSocket connection — similar to how a REST API with ReadableStream works. However, on the frontend, Its only displaying the first chunk then final completed message, not the intermediate streaming chunks. Here’s a simplified version of my setup: Backend (Django WebSocket Consumer): I’m using an async generator (handle_chat_request) to produce message chunks. async def receive(self, text_data): logging.info(f"WebSocket message received: {text_data}") try: data = json.loads(text_data) message_type = data.get("type") if message_type == "message": jwt_token = data.get("token") if not jwt_token: await self.send(json.dumps({"type": "error", "message": "Missing Authorization token."})) await self.close(code=4001) return user_message = data.get("content") user_id = data.get("user_id") combined_response = "" # Stream response chunks async for chunk in handle_chat_request(user_message, user_id, jwt_token): combined_response += chunk await self.send(json.dumps({"type": "ai_response_chunk", "content": chunk})) await asyncio.sleep(0) # Yield control to allow chunk sending # Send final complete message await self.send(json.dumps({"type": "ai_response_complete", "content": combined_response})) except Exception as e: logging.error(f"WebSocket error: {e}") await self.send(json.dumps({"type": "error", "message": "An error occurred."})) Frontend (Next.js WebSocket Client): I’m listening for incoming chunks and trying to append them to the latest bot message: const handleWebSocketMessage = (event) … -
How to resolve VSCode Pylance type checking error in Django
I'm encountering a type checking error in VSCode with Pylance when accessing serializer.validated_data["code"] in a Django project. The errors are: "__getitem__" method not defined on type "empty" Pylance Object of type "None" is not subscriptable Pylance The property type is inferred as: (property) validated_data: empty | Unknown | dict[Unknown, Unknown] | Any | None VSCode settings: "python.languageServer": "Pylance", "python.analysis.typeCheckingMode": "basic" I've defined the serializer class like, class InputSerializer(BaseSerializer): code = serializers.CharField( required=True, max_length=255, validators=[voucher_code_validator], ) How can I fix this? -
Failed to load resource: the server responded with a status of 401 (Unauthorized) - react & django
Am facing a crisis in my authentication system, during registration some of the fields like first and lastname, password, etc are not stored in the database which makes the login attempts return a 401 error, I have also tested with postman and in preview it shows invalid credentials. I have put a print statement in my registerView class to check if all the data fields reach the backend and it shows that indeed they do class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): print("Incoming Data from React:", request.data) serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response({"message": "User registered succefully"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried to play with my register serializer class which i believe might be causing the issues just to ensure that the missing fields can also be saved to the database but still not achieving results class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password', 'confirm_password', 'role', 'student_number', 'course_name', 'college', 'lecture_number', 'subject_taught', 'department' ] extra_kwargs = { 'password': {'write_only': True}, 'confirm_passwaord': {'write_only': True} } def validate(self, data): if data['password'] != data['confirm_password']: raise serializers.ValidationError({"password": "Passwords do not match."}) role = data.get('role') if role == 'student': if not all([data.get('student_number'), data.get('course_name'), … -
How do I enable a disabled button after moderators input some text into textarea using `hx-on`?
I want to disable the "Yes" button until moderators of my Django site provide a reason for banning users. Once the reason is provided in the textarea, then the "Yes" button would be enabled. It's a common pattern I've encountered when using React and Javascript, but since I'm using HTML and Django Templates for this project, I want to use HTMX for some interactivity. I'm still new using HTMX, so I'd appreciate some help, thanks! I've checked the questions on here, and I didn't find any answers for my question. Or am I using hx-on:input wrong in this context? I've also tried using hx-on:change but to no avail. I've looked into hx-disabled-elt but I don't think that's what I want. Because I'm not submitting a request just yet, I just want some interactivity for my form. I've also looked at this question but this requires me to communicate with the server, which I would like to minimise if I can. This is what I have currently and I'm not sure why it's not working: <form method="POST"> {% csrf_token %} <p>Please provide the reason for the ban.</p> <div class="input-group"> <textarea class="form-control" aria-label="Reason for ban" name="reason-for-ban" hx-on:input="htmx.removeClass(htmx.find(#yes-ban-this-user), 'disabled')"> </textarea> </div> <input type="submit" … -
Adding Markers to OpenStreetMap's Django/Python
I'm having issues with leaflet, and OpenStreetMap I cannot get a marker to be added for each job available. it just shows up as a blank map. Debugging shows that the information is being sent correctly but the map is not update. Here is the debug info. The list view works perfectly. and the map shows a correct marker when clicking on job from list view. (0.001) SELECT "users_job"."id", "users_job"."title", "users_job"."description", "users_job"."city", "users_job"."state", "users_job"."zip", "users_job"."latitude", "users_job"."longitude" FROM "users_job"; args=(); alias=default Jobs List: [{'id': 1, 'title': 'test job', 'description': 'this is a test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 2, 'title': 'testjob2', 'description': 'This is a test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 3, 'title': 'test job json', 'description': 'json test', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}, {'id': 4, 'title': 'jsontest2', 'description': 'asdofmasodfm', 'city': '*redacted*', 'state': '*redacted*', 'zip': '*redacted*', 'latitude': *redacted*, 'longitude': *redacted*}] (0.002) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2025-03-11T01:18:30.939183+00:00'::timestamptz AND "django_session"."session_key" = '*redacted*') LIMIT 21; args=(datetime.datetime(2025, 3, 11, 1, 18, 30, 939183, tzinfo=datetime.timezone.utc), '*redacted*'); alias=default (0.002) SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."username", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."email", "users_user"."phone_number", "users_user"."address", "users_user"."city", "users_user"."state", "users_user"."zip", "users_user"."latitude", … -
Can I integrate PyTorch with Django Web framework?
Hello so I'm looking to create some games on a website using Django. I would like to have some machine learning with the games so that the players can play against a machine learning model. Is this possible with the combination of Django and PyTorch? I heard about something called ONNX that helps serves model into the frontend and I just wanted to double check that works with Django and not exclusively with NodeJS. If it doesn't work then I'd appreciate any alternative solutions. Thanks for any insight -
Django Stripe Webhook not consistent Statuscode 500 sometimes 201
L.S. I am working on my first Django project and struggling with the Stripe integration. My webhook is acting inconsistently—it worked fine when running locally on localhost with the Stripe CLI. However, after deploying with Nginx and Gunicorn, it has become unreliable. Sometimes it goes through, but in most cases, I receive a 500 status code. I want to send an email to the customer with a PDF attachment when the checkout.session.completed webhook is triggered. I read that the webhook should return a 200 status code as quickly as possible; otherwise, Stripe might time out. Or could the issue be caused by a time difference between the request and the server? Regardless, I’m unsure how to properly fix this. I’d really appreciate any guidance from someone with experience. import datetime import stripe from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from webshop.models import Product, Customer, Order, OrderItem from django.core.mail import EmailMessage @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META.get("HTTP_STRIPE_SIGNATURE") endpoint_secret = settings.STRIPE_WEBHOOK_SECRET try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: return JsonResponse({"error": str(e)}, status=400) except stripe.error.SignatureVerificationError as e: return JsonResponse({"error": "Invalid signature"}, status=400) # Handle checkout success if event["type"] == "checkout.session.completed": … -
How to Prevent Screenshots and Screen Recording on a Payment Page (Django + Stripe Checkout)
I am working on a Django-based e-commerce website with Stripe Checkout for payments. I want to prevent users from taking screenshots or recording their screen on the payment page. ** What I Am Doing** Users are redirected to Stripe Checkout via a Django view: def checkout(request): session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{"price_data": {...}, "quantity": 1}], mode='payment', success_url="https://yourdomain.com/success/", cancel_url="https://yourdomain.com/cancel/", ) return redirect(session.url) The checkout URL looks like: https://checkout.stripe.com/c/pay/cs_test_a1iAFc5as6... ** What I Want to Achieve** Block screenshots (PrtSc, Snipping Tool, etc.) Prevent screen recording software Stop screen-sharing via Zoom, Google Meet, etc. ** My Questions** How can I prevent screenshots and screen recording? Is this possible in a web browser, or only in mobile apps? What is the most secure way to implement this? Any guidance would be greatly appreciated! -
@action got an unexpected keyword argument 'id'
class CustomUserViewSet(UserViewSet): serializer_class = UserSerializer pagination_class = PageNumberPagination permission_classes = [permissions.IsAuthenticated] def get_queryset(self): queryset = User.objects.all() return queryset @action(detail=False, methods=['put', 'delete'], url_path='me/avatar') def set_avatar(self, request): if request.method == 'PUT': serializer = SetAvatarSerializer( request.user, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_200_OK) user = request.user user.avatar.delete() user.save() return Response(status=status.HTTP_204_NO_CONTENT) @action(detail=True, methods=['post', 'delete'], url_path='subscribe') def set_or_delete_subscribe(self, request, pk=None): user = request.user user_to_subscribe = self.kwargs['id'] if request.method == 'POST': _, created = Subscription.objects.get_or_create(user=user, subscribed=user_to_subscribe) if created: return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': subscription = Subscription.objects.filter(user=user, subscribed=user_to_subscribe).delete() if subscription: return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_400_BAD_REQUEST) model of Subscription class Subscription(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='subscriptions' ) subscribed = models.ForeignKey( User, on_delete=models.CASCADE, related_name='subscribed' ) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'subscribed'], name='unique_subscription') ] urls router = DefaultRouter() router.register(r'tags', TagViewSet, basename='tags') router.register(r'recipes', RecipeViewSet, basename='recipes') router.register(r'ingredients', IngridientsViewSet, basename='ingredients') router.register(r'users', CustomUserViewSet, basename='users') TypeError: set_or_delete_subscribe() got an unexpected keyword argument 'id' [10/Mar/2025 08:38:23] "POST /api/users/11/subscribe/ HTTP/1.0" 500 88724 I can't figure out why get_object() expects id and doesn't accept pk ? Ьaybe I'm missing something, but I can't catch it. I need to subscribe to a user or delete them if already subscribed. -
Problem with the vite django integration (TypeError)
I'm currently working on integrating Vite with my Django project using the django-vite package. However, upon running the Django development server, I encounter the following error: TypeError: django_vite.core.asset_loader.DjangoViteConfig() argument after ** must be a mapping, not bool Project Setup: Django Version: 5.1.5 django-vite Version: [Specify Version] Vite Configuration: The vite.config.js is set to output build files to Django's static directory, and the manifest is enabled. Django Settings: django_vite is added to INSTALLED_APPS. DJANGO_VITE configuration is defined as follows: DJANGO_VITE = { "dev_mode": DEBUG, "manifest_path": os.path.join(BASE_DIR, "static", "manifest.json"), "static_url_prefix": STATIC_URL, } vite.config.ts export default defineConfig({ plugins: [react(), tailwindcss()], test: { globals: true, environment: "jsdom", setupFiles: "./src/setupTests.js", include: ["**/__tests__/**/*.{js,jsx,ts,tsx}"], }, base: "/static/", // Entspricht dem STATIC_URL in Django build: { outDir: "../backend/static/", // Pfad zum statischen Ordner von Django manifest: true, rollupOptions: { input: "src/main.jsx", // Haupteinstiegspunkt }, }, }); Error Details: The traceback indicates the error originates from the DjangoViteConfig class in the django_vite package: File "path_to_python_env\Lib\site-packages\django_vite\core\asset_loader.py", line 731, in _apply_django_vite_settings config = DjangoViteConfig(**config) TypeError: django_vite.core.asset_loader.DjangoViteConfig() argument after ** must be a mapping, not bool Configuration Verification: Ensured that the DJANGO_VITE settings are correctly defined as a dictionary. Dependencies Check: Verified that all related packages are up-to-date and compatible with each … -
Why is authenticate in drf not working and how do I make it work?
I am using Django with rest framework. Sign Up works fine, but when I log in, after passing the email and password to the backend, the authenticate() returns None even if the credentials are right. I am using a custom user model. Here are the relevant lines of code: models.py (does not include all fields) class CustomUserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email: raise ValueError('The user must enter a valid email.') email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **kwargs) class CustomUser(AbstractBaseUser, PermissionsMixin): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True) middle_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] groups = models.ManyToManyField( "auth.Group", related_name="customuser_set", blank=True ) user_permissions = models.ManyToManyField( "auth.Permission", related_name="customuser_set", blank=True ) viewsets.py @action(detail=False, methods=["post"], permission_classes=[AllowAny]) def login(self, request): email = request.data.get("email") password = request.data.get("password") user = CustomUser.objects.get(email=email) print(user) user = authenticate(request, email=email, password=password) # this returns None all … -
Django views' tests return 403 code instead of (presumably) 302
I'm testing views in my Django app. As the app is a backend of a forum site, I'm trying to test the creation, editing and deletion of a topic. Creation, editing and deletion of a topic are implemented in my app to work via redirect: create page redirects to a succefully created topic's page; editing the topic's initial comment redirects from the editing page to the edited topic's page; deletion page redirects to a subforum (a chapter of a forum) where the deleted topic had belonged. I presume (I'm not sure; and, most possibly, here is my mistake) that the successful redirect code is 302, and in the tests' assertion that's the code which should be checked. But for creation and editing of the topics tests return code 200, while for deletion test - code 403. And I, due to the lack of experience, hardly can explain why it happens this way and how to deal with it. views.py: class TopicListView(FilterView): paginate_by = 20 model = Topic template_name = "forum/subforum.html" slug_url_kwarg = 'subforum_slug' context_object_name = 'topics' filterset_class = TopicFilter def get_queryset(self): qs = self.model.objects.all() if self.kwargs.get('subforum_slug'): qs = qs.filter(subforum__slug=self.kwargs['subforum_slug']) return qs class ShowTopic(DetailView): model = Topic template_name = "forum/topic.html" slug_url_kwarg … -
How to save multiple related Django ORM instances in one go without separate database calls via the network?
Here is the example: article1 = Article(title="Global Warming", content="...") article2 = Article(title="Visiting Mars", content="...") comment1 = Comment(content="Some comment", article=article1) user1 = User(username="user1") some_updated_article.title = "updated title" article_to_delete.delete() In SQLAlchemy, I know you can save multiple instances to the database in one call as follows: db.session.add_all([article1, article2, comment1, user1]) db.session.commit() This approach sends all instructions to the database in one go (please correct me if I'm wrong). db.session.add_all() followed by db.session.commit() would work, and there wouldn’t be three separate calls to the database server. In Django, I know I can use bulk_create , bulk_update, for each model: Article.objects.bulk_create([article1, article2]) Comment.objects.bulk_create([comment1]) User.objects.bulk_create([user1]) Article.objects.bulk_update([some_updated_article], fields=["title"]) But this sends separate calls to the database server for each model. Is there a way to achieve something similar to SQLAlchemy's add_all() where I can send all objects in one go, regardless of the model? I was thinking about using transaction.atomic for this: with transaction.atomic(): Article.objects.bulk_create([article1, article2]) Comment.objects.bulk_create([comment1]) User.objects.bulk_create([user1]) Article.objects.bulk_update([some_updated_article], fields=["title"]) Using transaction.atomic() ensures that all operations either succeed or fail as one atomic transaction. However, in my use case, I don't want full rollback behavior. For example, if there’s an error while creating comments, I want to still save the articles and users successfully. I know … -
Django JSONField values aren't returned as a correct JSON-format in template when extracted using javascript
I have a model like class UserGroup(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=False, related_name="group_owner") name = models.CharField(max_length=128) group_users = models.JSONField(models.EmailField(), default=list, blank=True) def get_absolute_url(self): return reverse("user_group_instance", kwargs={"pk": self.pk}) now, in my in another app I filter for a list of UserGroup instances for the given user, and I parse that query-set to a ModelMultipleChoiceField. That works fine and such, the issue is that I want to extract the group_users in the template and add them to an array, using java-script, thus I have create a div which stores the (I would assume) json-array in the data-members attribute <div id="group-modal"> {% for group in form.groups.field.queryset %} <label> <input type="checkbox" class="group-checkbox" value="{{ group.id }}" data-members="{{ group.group_users|safe }}"> {{ group.name }} </label> <br> {% endfor %} </div> now, when I in javascript get the data from the data-members the returned string is not a json-object e.g it is "['hello@world', 'foo@bar']". The javascript is (simplified) document.getElementById("save-groups").addEventListener("click", function() { let selectedPeople = []; document.querySelectorAll(".group-checkbox:checked").forEach(checkbox => { let members = JSON.parse(checkbox.getAttribute("data-members")); selectedPeople = [...new Set([...selectedPeople, ...members])]; }); and the JSON.parse fails. I simply cannot wrap my head around why; I don't do any manually serialization of the json-data thus I let django do that stuff. I could …