Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe webhooks not firing in Django app during normal checkout flow
I'm integrating Stripe with my Django app (using Django REST Framework). I've set it up to accept POSTs, and when I use the Stripe CLI to trigger events, everything works perfectly. Example Stripe CLI command: stripe listen --forward-to localhost:8000/webhooks/api/v1/stripe-webhook/ When I run commands like stripe trigger checkout.session.completed I see the events in my server logs and my Django view is hit as expected: [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ price.created [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ charge.succeeded [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ payment_intent.succeeded [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ checkout.session.completed [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ payment_intent.created [evt_1R] [200] POST http://localhost:8000/webhooks/api/v1/stripe-webhook/ But when I go through my actual frontend flow (create a Checkout Session from my app, complete the payment in test mode, etc.), no webhooks are received at all. I see nothing in my Django logs. Nothing is received on my webhook endpoint. I also see no attempts or errors in the Stripe Dashboard's "Webhooks" section. Things I have tried: Registering both URLs in the Stripe Dashboard webhook settings. I am using test mode and test credentials. Stripe CLI and triggers work perfectly. Summary: Stripe CLI triggers work, real Stripe events from live app flow do not. No webhooks reach my server in normal payment flow, but do when … -
Django connection_created signal is causing problems when testing
In my django application I have a list of notification types and I want to allow customers to subscribe to one or more notification types. Each notification type has somewhat of a custom logic so the code of each notification has to be in a different class but I have created a singleton class that gathers all the notification type names and other metadata like description etc. I want to have a list in the database of all the supported notification types so that the relationship between customers and notification types can be stored in the database while customers subscribe to notification types. I want to have a notification type table so that I can store the metadata and a separate table to store the many-to-many relationship between customers and notifications. That is where connection_created signal comes in. I have created the following signal that creates the notification type items in the database when the connection_created signal is received so they get auto-updated when I am changing the code: from django.db.backends.signals import connection_created from django.db.backends.postgresql.base import DatabaseWrapper from django.dispatch import receiver from notification_type_singleton import NotificationTypeSingleton from models import NotificationType @receiver(connection_created, sender=DatabaseWrapper) def create_or_update_notification_type(sender, **kwargs): exiting_ids = [] for _, notification_type … -
535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled
I have a website that uses an email contact form. Recently been told it does not work. When I recreated the error in development I got the error 535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled. I read online that basic authentication has been switched off by Microsoft. I am unsure how to resolve this. Is there a new way to authenticate? I cannot find anything that will allow a user to provide these simple details to send an email to our inbox. I am using Django and the following code that did work before. html = render_to_string('emails/contact_form.html', { 'first_name': first_name, 'last_name': last_name, 'email': email, 'content': content }) send_mail('Message', content, EMAIL_HOST_USER, [EMAIL_HOST_USER], html_message=html) -
Stripe: "No signatures found matching the expected signature for payload" using Django Rest Framework and request.body
I'm integrating Stripe webhooks into my API, which is built with Django Rest Framework (DRF). Here’s my webhook view: class StripeWebhookView(APIView): permission_classes = [AllowAny] # Public webhook def post(self, request, *args, **kwargs): payload = request.body sig_header = request.headers.get('stripe-signature') try: event = stripe.Webhook.construct_event( payload=payload, sig_header=sig_header, secret=settings.STRIPE_SIGNING_SECRET ) except ValueError as e: print(f"Invalid payload: {e}") return Response(status=status.HTTP_400_BAD_REQUEST) except stripe.error.SignatureVerificationError as e: print(f"Signature verification failed: {e}") return Response(status=status.HTTP_400_BAD_REQUEST) # ... webhook logic ... return Response(status=200) I get: [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 200 0 Invalid signature: No signatures found matching the expected signature for payload Bad Request: /webhooks/stripe-webhook/ [...] "POST /webhooks/stripe-webhook/ HTTP/1.1" 400 0 I’ve already double-checked that my STRIPE_SIGNING_SECRET is correct, and my endpoint is set up correctly in the Stripe dashboard. I am using request.body directly (not request.data), as suggested in other answers, but the error persists. Has anyone successfully used Stripe webhooks with Django Rest Framework and managed to pass signature verification? I have carefully read and tried all the solutions mentioned in this post I am using request.body (not request.data) … -
Using list which depends on another list in excel using python
I have a requirement to create dependent dropdowns in excel using python. import os import openpyxl from openpyxl.styles import Border, Side, PatternFill, Font, Alignment, numbers from openpyxl.worksheet.datavalidation import DataValidation from openpyxl.workbook.defined_name import DefinedName def create_dynamic_excel_bytes(sheets_config, file_name): wb = openpyxl.Workbook() ws_hidden = wb.create_sheet("Hidden") hidden_col = 1 path_url = "/home/downloads/dravoka-downloadexcel/" file_path = os.path.join(path_url, file_name) # ✅ Add global EmptyRange placeholder empty_col_letter = openpyxl.utils.get_column_letter(hidden_col + 100) ws_hidden.cell(row=1, column=hidden_col + 100, value="") wb.defined_names.add( DefinedName("EmptyRange", attr_text=f"Hidden!${empty_col_letter}$1") ) for sheet_idx, sheet_conf in enumerate(sheets_config): if sheet_idx == 0: ws = wb.active ws.title = sheet_conf["sheet_name"] else: ws = wb.create_sheet(sheet_conf["sheet_name"]) columns = sheet_conf["columns"] num_rows = sheet_conf.get("num_rows", 100) # Create border style border = Border( left=Side(border_style="thin"), right=Side(border_style="thin"), top=Side(border_style="thin"), bottom=Side(border_style="thin"), ) # Create header style header_fill = PatternFill(start_color="475E75", end_color="475E75", fill_type="solid") header_font = Font(bold=True, color="FFFFFF") # White color header_alignment = Alignment(horizontal="center", vertical="center") for col_idx, col in enumerate(columns, start=1): cell = ws.cell(row=1, column=col_idx, value=col["header"]) cell.fill = header_fill cell.font = header_font cell.alignment = header_alignment cell.border = border for col_idx, col in enumerate(columns, start=1): col_letter = openpyxl.utils.get_column_letter(col_idx) if col["type"] == "dropdown": for i, val in enumerate(col["dropdown_values"], start=1): ws_hidden.cell(row=i, column=hidden_col, value=val) range_name = f"{sheet_conf['sheet_name']}_{col['header']}".replace(" ", "_") range_ref = ( f"Hidden!${openpyxl.utils.get_column_letter(hidden_col)}$1:" f"${openpyxl.utils.get_column_letter(hidden_col)}${len(col['dropdown_values'])}" ) wb.defined_names.add(DefinedName(name=range_name, attr_text=range_ref)) dv = DataValidation(type="list", formula1=f"={range_name}", allow_blank=True) ws.add_data_validation(dv) for row in range(2, num_rows + … -
JsonField in Django Admin as Inline
I have a JsonField in my Model, its structure is a dict. class MyModel: final_result = models.JSONField() But it's pretty big, and it's hard to edit it with any JSON widget. So I thought, that maybe I need to parse/split it to several 'custom' fields. jsonfield = { "key1": "value1", "key2": "value2", "key3": [ {"inner_key_1": "inner_value_1", "inner_key_2": "inner_value_2", etc} ] } Given this JSON data, I would like to have fields: key1, key2 (which is easy), and here's the problem - key3, which is list of dicts. Can I somehow display them like Inlines? With fields - inner_key_1, inner_key_2 (etc) So I can edit each element of list delete element with button add another element with preset fields When I try to use inlines - it says it needs a model, but I don't have a model for this json. Proxy models and abstract models give errors. Forms, formsets (AI recommendations) don't work too. I tried using inlines, forms, formsets, with a help from AI)) -
Trying to do Selenium testing in Django in Docker getting ERR_CONNECTION_REFUSED
I am trying to get Selenium testing going in Docker with Django. But I keep getting ERR_CONNECTION_REFUSED when using the live_server_url. I have tried to use django's container with f"http://django:{self.port}{reverse('account_login')}" I have also tried to use the ip address of the django container, but that doesn't work either. The selenium portion of the docker compose file is from https://github.com/SeleniumHQ/docker-selenium/blob/trunk/docker-compose-v3.yml docker compose file services: django: container_name: django_dev env_file: - ../environments/example.env image: &django django build: context: .. dockerfile: docker_development/Dockerfile command: python manage.py runserver 0.0.0.0:8006 volumes: - ../site:/code ports: - "8006:8006" depends_on: - db celery: container_name: celery_dev image: *django restart: 'no' entrypoint: celery -A project worker --beat --scheduler django --loglevel=info volumes: - ../site:/code env_file: - ../environments/example.env depends_on: - db - rabbitmq3 - django db: command: postgres container_name: devdb image: postgres:17 restart: 'no' #always env_file: - ../environments/example.env ports: - "5432:5432" volumes: - postgres-data:/var/lib/postgresql/data rabbitmq3: container_name: "rabbitmq_dev" image: rabbitmq:3-management-alpine env_file: - ../environments/example.env ports: - "5672:5672" - "15672:15672" chrome: image: selenium/node-chrome:4.35.0-20250808 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub edge: image: selenium/node-edge:4.35.0-20250808 platform: linux/amd64 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub firefox: image: selenium/node-firefox:4.35.0-20250808 shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub selenium-hub: image: selenium/hub:4.35.0-20250808 container_name: selenium-hub ports: - "4442:4442" - "4443:4443" - … -
'RegisterSerializer' object has no attribute '_has_phone_field'
dj-rest-auth library has been returning this error when I send a request into the /registration endpoint from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer class RegSerializer(RegisterSerializer): phone = serializers.CharField(required = False) def get_cleaned_data(self): data= super().get_cleaned_data() data['phone']=self.validated_data.get("phone","") return data Error message: AttributeError at /auth/dj-rest-auth/registration/ 'RegisterSerializer' object has no attribute '_has_phone_field' Error location: C:\...\site-packages\allauth\account\adapter.py, line 338, in save_user which points to this.. def save_user(self, request, user, form, commit=True): from .utils import user_email, user_field, user_username data = form.cleaned_data first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") username = data.get("username") user_email(user, email) user_username(user, username) if first_name: user_field(user, "first_name", first_name) if last_name: user_field(user, "last_name", last_name) if "password1" in data: user.set_password(data["password1"]) elif "password" in data: user.set_password(data["password"]) else: user.set_unusable_password() self.populate_username(request, user) if commit: user.save() if form._has_phone_field: phone = form.cleaned_data.get("phone") if phone: self.set_phone(user, phone, False) return user Tried to extend the RegisterSerializer that exists in the package, still didn't work, I followed the docs thoroughly but the issue persists, I don't see where the problem lies. -
Django REST API endpoints URL paths
I have a Django 4.2 app with Postgres DB and REST API. My urls.py contains this path in urlpatterns: path('create/<int:pk>/<str:name>/', ComponentCreate.as_view(), name='create-component') ComponentCreate in views.py relates to a simple DB table (component) with id as integer primary key and name as the only other column. views.py has: class ComponentCreate(generics.CreateAPIView): queryset = Component.objects.all(), serializer_class = ComponentSerializer lookup_field = "id" models.py has: class Component(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'component' serializers.py has: class ComponentSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField() class Meta: model = Component fields = ('id', 'name') I am trying to use the API to add a row to the component table using e.g. as below (where app is called SystemTestDB): curl -X POST http://127.0.0.1:8000/SystemTestDB/create/2/whatever/ However this fails with response: {"id":["This field is required."],"name":["This field is required."]} I have other endpoints which do work correctly e.g. with path: path('delete/<int:pk>/', ComponentDelete.as_view(), name='delete-component') In that case evidently id is being passed via int:pk, whilst in the failing case neither id nor name are set in the Request. Have I set the URL path incorrectly, or is there something wrong with model/view/serializer ? -
Deploy a dockerized monorepo to Railway
I'm trying to deploy my dockerized monorepo (Django & Next.js) project to Railway but I keep failing. My folder structure railway.tom [build] builder = "dockerfile" # Frontend service [services.frontend] builder = "dockerfile" rootDirectory = "client" # Backend service [services.backend] builder = "dockerfile" rootDirectory = "services/properties" I keep getting this error from Railway: Dockerfile Dockerfile does not exist -
DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread
I'm having the following issue, when I try to execute my Django tests: /Users/myUser/Desktop/myProject-py/src/project/project/billing_v2/tests/test_accounting_integration_heading.py::AccountingIntegrationHeadingAPITests::test_create_accounting_integration_heading failed with error: Test failed with exception request = <SubRequest '_django_setup_unittest' for <TestCaseFunction test_makemigrations_command>> django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0x10602ae80> @pytest.fixture(autouse=True, scope="class") def _django_setup_unittest( request, django_db_blocker: "_DatabaseBlocker", ) -> Generator[None, None, None]: """Setup a django unittest, internal to pytest-django.""" if not django_settings_is_configured() or not is_django_unittest(request): yield return # Fix/patch pytest. # Before pytest 5.4: https://github.com/pytest-dev/pytest/issues/5991 # After pytest 5.4: https://github.com/pytest-dev/pytest-django/issues/824 from _pytest.unittest import TestCaseFunction original_runtest = TestCaseFunction.runtest def non_debugging_runtest(self) -> None: self._testcase(result=self) try: TestCaseFunction.runtest = non_debugging_runtest # type: ignore[assignment] > request.getfixturevalue("django_db_setup") .venv/lib/python3.8/site-packages/pytest_django/plugin.py:490: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.8/site-packages/pytest_django/fixtures.py:122: in django_db_setup db_cfg = setup_databases( .venv/lib/python3.8/site-packages/django/test/utils.py:179: in setup_databases connection.creation.create_test_db( .venv/lib/python3.8/site-packages/django/db/backends/base/creation.py:59: in create_test_db self.connection.close() .venv/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) .venv/lib/python3.8/site-packages/django/db/backends/base/base.py:285: in close self.validate_thread_sharing() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to execute a multi-statement Snowflake SQL script (DECLARE, DDL, DML, CASE) from Python with parameters and fetch SELECT results?
I’m new to Python and Snowflake’s scripting blocks. I want to keep a multi-statement Snowflake SQL script in a .sql file and execute it from Python with parameters. The script may include DECLARE, DDL, DML, CASE logic — basically SP-like behavior — and I want to capture any SELECT result sets if present. Example script (simplified): BEGIN -- Declare a variable using Snowflake scripting DECLARE v_admin STRING DEFAULT :admin_user; -- Create a temporary table CREATE TEMP TABLE temp_data ( tenant STRING, client STRING, user_id STRING, use_mm STRING, access_level STRING ); -- Two inserts INSERT INTO temp_data (tenant, client, user_id, use_mm, access_level) VALUES ('101', '202', 'admin_user', 'true', NULL), ('102', '203', 'guest_user', 'false', NULL); -- CASE update using the declared variable UPDATE temp_data SET access_level = CASE WHEN use_mm = 'true' AND user_id = v_admin THEN 'full' WHEN use_mm = 'true' THEN 'limited' ELSE 'none' END; -- Return results SELECT * FROM temp_data; END; What I need: Execute the file from Python, bind parameters (e.g., admin_user), and support multiple statements. If the script contains one or more SELECTs, fetch results (ideally the last SELECT); otherwise just execute. Keep temp tables ephemeral (session-scoped). Questions: Can I achieve stored-procedure-like behavior by keeping the SQL … -
InlineKeyboardButton with callback_data doesn't work
InlineKeyboardButton with callback_data doesn't work. When I click on it, nothing happens. Here is how I create the button: from django.apps import apps from asgiref.sync import sync_to_async from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo from telegram.ext import CommandHandler, ApplicationBuilder, MessageHandler, filters, CallbackQueryHandler async def start(self, update: Update, context): keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("Already registred", callback_data="already_registered")], [InlineKeyboardButton("Register", web_app=WebAppInfo(url=WEB_APP_URL))] ]) await update.message.reply_text( "Welcome", reply_markup=keyboard ) return This is the callback query handler: async def button(self, update: Update, context): query = update.callback_query if not query: return await query.answer() if query.data == "already_registered": await context.bot.send_message( chat_id=update.message.chat_id, text='Good' ) return and this is how I run: def run(self): TOKEN = apps.get_model('app.Config').objects.get_mailing_tg_bot_token() app = ApplicationBuilder().token(TOKEN).build() app.add_handler(CommandHandler('start', self.start)) app.add_handler(CallbackQueryHandler(self.button)) -
Snyk flags code as path traversal vulnerability but the code seems ok
In my django python application I have such functions: def get_sanitized_file_path(file_path: str) -> Path: ALLOWED_BASE_DIR = Path(settings.MEDIA_ROOT).resolve() if not file_path: raise SuspiciousOperation("No file path provided") try: file_path = os.path.normpath(file_path) if ".." in file_path: raise SuspiciousOperation("Path traversal attempt detected") # Security: Prevent path traversal - this will raise ValueError if outside MEDIA_ROOT request_path = Path(file_path).resolve() request_path.relative_to(ALLOWED_BASE_DIR) if not request_path.exists(): raise FileNotFoundError("File not found") if not request_path.is_file(): raise SuspiciousOperation("Path is not a regular file") return request_path except (ValueError, OSError, PermissionError) as e: raise SuspiciousOperation(f"File access error: {e}") def load_file(file_path): file_path = get_sanitized_file_path(file_path) if not file_path: raise exceptions.FileNotFoundException if not os.path.exists(file_path): raise exceptions.FileNotFoundException try: with open(file_path, "rb") as file: file_data = io.BytesIO(file.read()) except Exception as e: raise exceptions.FileReadError from e return file_data def render_file(file_path, filename=None, content_type="application/pdf"): file_data = load_file(file_path) filename = filename or file_util.get_filename(file_path) return render_response(file_data, filename, content_type) def render_response(file_data, filename, content_type="application/pdf"): response = FileResponse(file_data, content_type=content_type, as_attachment=True, filename=filename) set_response_props(response, filename) return response and somewhere in my code I calling the render_file function: file_path = get_file_path() # returns a posix path file_path = get_sanitized_file_path(file_path) render_file(file_path) # gets flagged by snyk Even though I'm sanitizing my file path both before calling the method and inside the method called, Snyk code still flags the line render_file(file_path) … -
How to handle customer.subscription.created if a organization(tenant) doesn’t exist yet in Stripe webhook?
I'm using Django and Stripe for a multi-tenant SaaS. I register users and organizations manually from a view, and I create the customer and subscription using Stripe API before saving to the database. class TestRegisterView(APIView): permission_classes = () def post(self, request, *args, **kwargs): user_data = request.data.get('user', None) organization_data = request.data.get('organization', None) payment_data = request.data.get('payment', None) if None in [user_data, organization_data, payment_data]: return Response(data={'message': 'Missing data'}, status=400) price = PriceModel.objects.filter(stripe_price_id=payment_data['price_id']) if not price.exists(): return Response(data={'msg': 'Price not found'}, status=400) user = UserModel.objects.filter( Q(email=user_data['email']) | Q(username=user_data['username'])) if user.exists(): return Response(data={'msg': 'Customer with that email or username already exists'}, status=400) organization = OrganizationModel.objects.filter( Q(name=organization_data['name']) | Q(company_email=organization_data['company_email']) | Q(phone_number=organization_data['phone_number'])) if organization.exists(): return Response(data={'message': 'Organization already exists'}, status=400) user_serializer = POSTUserSerializer(data=user_data) organization_serializer = POSTOrganizationSerializer(data=organization_data) if user_serializer.is_valid() and organization_serializer.is_valid(): stripe_connection = StripeSingleton() try: stripe_customer = stripe_connection.Customer.create( email=payment_data['email'], name=f"{user_data['first_name']} {user_data['last_name']}", ) except Exception: return Response(data={'msg': 'Error creating Stripe customer'}, status=400) try: subscription = stripe_connection.Subscription.create( customer=stripe_customer.id, items=[{'price': payment_data['price_id']}], payment_behavior='default_incomplete', expand=['latest_invoice.confirmation_secret'], ) except Exception: return Response(data={'msg': 'Error creating Stripe subscription'}, status=400) try: with transaction.atomic(): user = user_serializer.save() organization = organization_serializer.save( owner_id=user.id, stripe_customer_id=stripe_customer.id ) user.organization = organization user.save() with schema_context(organization.schema_name): UserLevelPermissionModel.objects.create( user=user, level=UserLevelPermissionModel.UserLevelEnum.ADMIN, ) except Exception: stripe_connection.Subscription.delete(subscription.id) stripe_connection.Customer.delete(stripe_customer.id) return Response(data={'msg': 'Error creating user or organization'}, status=400) return Response(data={ 'subscription_id': subscription.id, … -
testing a complex multipart custom django form
I have 2 complex custom form classes; each class contain several subforms (model form, formset and sometimes nested formset). I have written tests for both of them : tests of the form methods (init, full_clean, is_valid) using post data. I am looking for a way to test the creation of the form with the renderer. In the view tests, using request factory, the form is created but the forms within the formset are not created. When I do manual testing of the form with the test server, I encounter some errors that are notcovered by my tests -
Items Not Getting Added To Anonymous Users Cart?
i wanna make non logged in users can added items to thier cart but when i click add to cart no item getting added to thier cart this is my views.py : from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId … -
Implementation of MultiPolygonZMField in GeoDjango/django
I have an .shp file and the ogrinfo resulted as follow # ogrinfo -so AnalysisV1.shp AnalysisV1 INFO: Open of `AnalysisV1.shp' using driver `ESRI Shapefile' successful. Layer name: AnalysisV1 Metadata: DBF_DATE_LAST_UPDATE=2025-06-23 Geometry: 3D Measured Polygon Feature Count: 223252 Extent: (105.072679, -8.808389) - (116.270615, -4.224575) Layer SRS WKT: GEOGCRS["WGS 84", DATUM["World Geodetic System 1984", ELLIPSOID["WGS 84",6378137,298.257223563, LENGTHUNIT["metre",1]]], PRIMEM["Greenwich",0, ANGLEUNIT["degree",0.0174532925199433]], CS[ellipsoidal,2], AXIS["latitude",north, ORDER[1], ANGLEUNIT["degree",0.0174532925199433]], AXIS["longitude",east, ORDER[2], ANGLEUNIT["degree",0.0174532925199433]], ID["EPSG",4326]] Data axis to CRS axis mapping: 2,1 OBJECTID_1: Integer64 (10.0) FID_jawa_p: Integer64 (10.0) objectid: Integer64 (10.0) kriteria: String (50.0) kodeprov: Real (19.11) I've tried to generate the model using ogrinspect ./manage.py ogrinspect AnalysisV1.shp Analysis --srid=4326 --mapping --multi and model generated as follow from django.contrib.gis.db import models class Analysis(models.Model): objectid_1 = models.BigIntegerField() fid_jawa_p = models.BigIntegerField() objectid = models.BigIntegerField() kriteria = models.CharField(max_length=50) kodeprov = models.FloatField() geom = models.MultiPolygonZMField(srid=4326) When I check the django.contrib.gis.db.models, there is no MultiPolygonZMField implementation. How the ogrinspect use that Field whilst MultiPolygonZMField not defined? Is there any MultiPolygonZMField implementation on GeoDjango? or model field compatible ? -
Why does my Django models.Manager return all objects on a relationship?
I don't particularly understand what's going on here, but it seems that super().get_queryset() doesn't do what I think it does? I have 1:N relationship, and the default FK reverse lookup works: >>> for thing in this.thing_set.all(): ... print(thing.this) Each one of these is This. However, with my customized: >>> for thing in this.thing_set.by_date(): ... print(thing.this) Will produced This and `That* class ThingByDateManager(models.Manager): def by_date(self): return super().get_queryset().order_by("start_time") That's all there is. class This(models.Model): name = models.CharField(max_length=255, primary_key=True) class Thing(models.Model): start_time = models.DateTimeFiled() name = models.CharField(max_length=255) this = models.ForeignKey(This, on_delete=models.CASCADE) objects = ThingByDateManager() (might not have those models perfectly written, but I'm hoping it's just something silly with the queryset or something) Why doesn't this correctly filter my objects by this, instead returning all of the Things? -
How do i make the names appear more to the left and reduce the spacing between the checkbox and the name?
I’m rendering a Django form field (CheckboxSelectMultiple) inside a custom dropdown. The checkboxes and labels (names) are visually shifted to the right. I want the dropdown to look like a clean checklist, with all checkbox icons aligned in the same column and the text starting immediately to the right of the checkboxes, without extra indentation.checkbox and names far to the right {{ form.non_field_errors }} {% for field in form %} <div style="margin-bottom: 1rem;"> {{ field.label_tag }}<br> {% if field.name == 'team_members' %} <div class="dropdown"> <button type="button" onclick="toggleDropdown(this)">Select Team Members</button> <div class="dropdown-content" style="display:none;"> {% for checkbox in field %} <label style="display: flex; align-items: center; gap: 6px; margin-bottom: 6px;"> {{ checkbox.tag }} <span style="font-size: 1rem;">{{ checkbox.choice_label }}</span> </label> {% endfor %} </div> </div> {% else %} {{ field }}<br> {% endif %} {{ field.errors }} </div> {% endfor %} <style> .dropdown { position: relative; display: inline-block; } .dropdown-content { position: relative; background: #fff; border: 1px solid #ccc; padding: 10px; z-index: 100; min-width: 220px; max-height: 220px; overflow-y: auto; box-shadow: 0 2px 8px rgba(0,0,0,0.08); display: flex; flex-direction: column; } .dropdown-content label { display: flex; align-items: center; margin-bottom: 6px; cursor: pointer; justify-content: flex-start; gap: 2px; /* smaller gap */ } .dropdown-content input[type="checkbox"] { margin-right: -5px; … -
Stripe Subscription: latest_invoice.payment_intent raises AttributeError: payment_intent
I'm trying to create a subscription in Stripe using Python and the official library, with the goal of obtaining the client_secret from the initial invoice's PaymentIntent to complete payment on the frontend. Here is the code I'm using: import stripe stripe.api_key = 'sk_test_...' price_id = 'price_...' # Example subscription = stripe.Subscription.create( customer=customer.id, items=[{'price': price_id}], payment_behavior='default_incomplete', expand=['latest_invoice.payment_intent'], ) I want to access: subscription.latest_invoice.payment_intent.client_secret But I get the error: AttributeError: payment_intent What I've checked so far The subscription is created successfully. The parameter expand=['latest_invoice.payment_intent'] is included to embed the payment_intent object. I've verified that the invoice (latest_invoice) exists. However, the payment_intent field is missing from the latest_invoice object. Questions Why is payment_intent missing from latest_invoice when creating the subscription with payment_behavior='default_incomplete' and expanding the field? How should I obtain the client_secret to confirm payment on the frontend using Stripe.js in these cases? -
Error d"MIME (« text/html ») incorrect (X-Content-Type-Options: nosniff)" on deploy Django project with gunicorn and Apache
I'm trying to deploy a Django project with Gunicorn and Apache. The gunicorn is configured and working --> no problem on this side The problem is with the statics files, i configure an apache conf : <VirtualHost *:80> ProxyPass /static/ ! ProxyPass / http://0.0.0.0:8002/ ProxyPassReverse / http://0.0.0.0:8002/ Alias /static/ /opt/livraison/apache/DEV <Directory /opt/livraison/apache/DEV> Require all granted </Directory> # Possible values for LogLevel : debug, info, notice, warn, error, crit, alert, emerg. LogLevel info ErrorLog /logs/PASPE_DEV/apache_error.log CustomLog "/logs/PASPE_DEV/access_log/apache.log" "%h %l %u %t \"%r\" %>s %b" </VirtualHost> And it seem that my static files are redirect to gunicorn so on port 8002 and not 80. and i got this error : adresse « http://server:8002/static/SuiviInstall/css/home.css » a été bloquée en raison d’un type MIME (« text/html ») incorrect (X-Content-Type-Options: nosniff) How can i handle this error ? -
How to re-compile static/css/site-tailwind.js file in Django project
I'm developping a Django project inside a docker container, but am running into a problem. I cannot get the docker container to recompile the static/css/site-tailwind.css file. I'm trying to include components which are declared in a assets/styles/site-tailwind.css file, but however I build the image, it does not compile the static file anew... Anyone has an idea on how to do this ? -
Unable to create POST request via HTMX for WebSocket
When trying to send a form in real-time chat, a GET request (HTTP GET /?csrfmiddlewaretoken=some_csrf) appears in the console instead of POST, and the program does not reach the consumer. Django-v5.2.4, daphne-v4.2.1 chat.html {% extends 'layouts/blank.html' %} {% block content %} <wrapper class="block max-w-2xl mx-auto my-10 px-6"> {% if chat_group.groupchat_name %} <div class="flex justify-between"> <h2>{{ chat_group.groupchat_name }}</h2> {% if user == chat_group.admin %} <a href="{% url 'edit-chatroom' chat_group.group_name %}"> <div class="p-2 bg-gray-200 hover:bg-blue-600 rounded-lg group"> <svg class="fill-gray-500 group-hover:fill-white" width="16" height="16" <path d="M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"></path> </svg> </div> </a> {% endif %} </div> {% endif %} <div id="chat_window" class="h-[45rem] flex flex-col bg-gray-800 rounded-2xl shadow-2xl relative p-1"> <div class="flex justify-center text-emerald-400 bg-gray-800 p-2 sticky top-0 z-10"> {% if other_user %} <div id="online-icon" class="gray-dot absolute top-2 left-2"></div> <a href="{% url 'profile' other_user.username %}"> <div class="flex items-center gap-2 p-4 sticky top-0 z-10"> <img class="w-10 h-10 rounded-full object-cover" src="{{ other_user.profile.avatar }}" /> <div> <span class="font-bold text-white">{{ other_user.profile.name }}</span> <span class="text-sm font-light text-gray-400">@{{ other_user.username }}</span> </div> </div> </a> … -
Issue with Django product quantity
I want to make sure that the selected quantity by the buyers is passed to the cart and the placed order, how will I do that