Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form won't send post request
Hello I'm rebuilding my inventory application with the use of django forms and jinja template syntax I can't get the form to send a post request. here's my form in the template {% extends "inventory/base.html" %} {% block content%} <form action="inventory/stock/{{part_id}}" method="post">{% csrf_token %} {{form}}</form> <button type="submit" name="confirm" >Confirm</button> <button type="submit" name="cancel">Cancel</button> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }}</li> {% endfor %} </ul> {% endif %} {% endblock %} here's my URL: path('stock/<int:part_id>/', views.add_stock_page, name='add_stock') here's my View: @login_required def add_stock_page(request, part_id): print('hi') template= loader.get_template('inventory/addStock.html') user= request.user form = StockForm() title = 'Add Stock' if 'confirm' in request.POST: print('confirm') messages.info(request,'confirm') if 'cancel' in request.POST: messages.info(request,'cancel') return render(request, 'inventory/addStock.html',{ 'user':user, 'form':form, 'title':title, 'part_id':part_id # 'messages':messages }) here's my form: class StockForm(forms.ModelForm): quantity = forms.IntegerField(required=True) price = forms.DecimalField(required=True) class Meta: model = Stock fields = [ 'supplier_id', 'brand_id', 'price' ] labels ={ 'quantity':'Quantity', 'supplier_id':'Supplier', 'brand_id':'Brand', 'price':'Price' } -
set priority on Queryset in django
this is my product and category model: class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): ... category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) I want a list of all products with priority order. e.g. categories_ids = [3,5,1,4,2] now I want data to order like this [product_with_category_3, product_with_category_3, product_with_category_3, product_with_category_5, product_with_category_1, product_with_category_1, ...] -
Django Admin Theme Switching Between Grappelli and Jazzmin Not Working (Session-Based)
Problem Statement: I am working on a Django e-commerce project and want users to switch between two admin themes: Grappelli and Jazzmin using Django sessions. I have implemented a session-based theme switcher, but: The admin panel always loads Grappelli by default. The switch button appears, but clicking it does not apply the correct theme. After switching to Jazzmin, I get a "Page Not Found" error (404). Project Setup 1. Installed Apps (settings.py) INSTALLED_APPS = [ "grappelli", # Defaulting to Grappelli "jazzmin", # Want to switch between these two "colorfield", "core.apps.CoreConfig", # My core app "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.humanize", ] Grappelli is loading by default, even when the session should switch to Jazzmin. 2. Middleware for Dynamic Theme Switching (core/middleware.py) from django.utils.deprecation import MiddlewareMixin class DynamicAdminThemeMiddleware(MiddlewareMixin): def process_request(self, request): from django.conf import settings if request.session.get("admin_theme") == "grappelli": settings.INSTALLED_APPS = ["grappelli"] + [app for app in settings.INSTALLED_APPS if app != "jazzmin"] else: settings.INSTALLED_APPS = ["jazzmin"] + [app for app in settings.INSTALLED_APPS if app != "grappelli"] I suspect modifying settings.INSTALLED_APPS dynamically might not be effective. Does Django require a restart for INSTALLED_APPS changes to take effect? Middleware is included in settings.py: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "core.middleware.DynamicAdminThemeMiddleware", # Custom middleware … -
Django: Best way to create logs when updating a model in bulk
I am developing a Django system where I have a main model and a log/history model to record changes. My main model: class Modelo(models.Model): user_a = models.ForeignKey(User, on_delete=models.CASCADE, related_name="delegated_signatures") user_b = models.ForeignKey(User, on_delete=models.CASCADE, related_name="received_delegations") is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) And the history model: class ModeloLogHistory(models.Model): modelo = models.ForeignKey(Modelo, on_delete=models.CASCADE) changed_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) change_type = models.CharField(max_length=50, choices=ChangeType.CHOICES) previous_data = models.JSONField(null=True, blank=True) new_data = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) The logic works well for individual changes, but there is a scenario where an administrator can deactivate all records at once (is_active = False). This could generate a large volume of logs in the database, making me wonder about the best approach to handle these changes efficiently. -
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 …