Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + python --> problem with polish characters like "ą" "ę" "ł"
Ciao! I am a beginner in Django & Python. I want to create a simple blog. I followed a step-by-step tutorial from this video → [YouTube link]https://www.youtube.com/watch?v=2MkULPXXXLk&t=865s and I have issue. When I create a category with Polish characters like "ą", "ę", it works. However, when I try to assign a post to this category, it doesn’t work. I spent some time trying to fix it but had no success. If I understand correctly, Python compares the category name "Łódź" with "Łódź" after URL transformation or something like that. For example: Łódź == odz → False Because of this, I can't see posts in the "Łódź" category. Here is my GitHub repo: [GitHub link] https://github.com/marekpno/problem MD -
Specifying get methods for nested serializers
In the case of nested serializers, is there a way to specify a method that will get the data? class AuthorSerializer(ModelSerializer): .... class BookSerializer(ModelSerializer): authors = AuthorSerializer(many=True) .... In this example, I would like to intercept and modify how BookSerializer gets the authors. How do I accomplish this? -
Django error with SSL and Azure Flexible MySQL
I'm doing a MySQL migration to an Azure MySQL Server. Which I don't have the control on the configuration. I managed to connect to it with a simple python script, but faking the TLS flag with pymysql. from azure.identity import ManagedIdentityCredential import pymysql # Get Managed Identity Token credential = ManagedIdentityCredential() token_msi = credential.get_token( "https://ossrdbms-aad.database.windows.net/.default" ).token deploy_env = "dev" application_name = "my_app" # Define connection parameters connection = pymysql.connect( host="xxxxxxxxxxxxxxxxxxxx.mysql.database.azure.com", user=f"{application_name}_{deploy_env}", password=token_msi, db=f"{application_name}_{deploy_env}", ssl={"fake_flag_to_enable_tls": True} ) # Execute a query query = "SHOW DATABASES" with connection.cursor() as cursor: cursor.execute(query) print(cursor.fetchall()) So this works. I managed to dump my old database and import it to the new one using the mysql cli. But now I'm trying to make my Django app connect to it. In my Django settings.py: deploy_env = "dev" application_name = "my_app" DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": f"{application_name}_{deploy_env}", "USER": f"{application_name}_{deploy_env}", "PASSWORD": None, # Token will be assigned dynamically "HOST": f"xxxxxxxxxxxxx.mysql.database.azure.com", "PORT": 3306, } } get_db_token() Here is the get_db_token function: import os import django.conf as conf from azure.identity import ManagedIdentityCredential def get_db_token(): azure_credential = ManagedIdentityCredential() token = azure_credential.get_token( "https://ossrdbms-aad.database.windows.net" ).token conf.settings.DATABASES["default"]["PASSWORD"] = token When making a test with python manage.py dbshell I can see all my … -
Using pghistory with custom event table names
I'm currently testing pghistory for our Django project. I set up a few models to be tracked. As a convention our model names are different from the actual table names - these are defined in the Meta class like so: class Delivery(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deliveries', on_delete=models.PROTECT, editable=False) ... class Meta: db_table = 'ep_delivery' When I decorate the model with @pghistory.track() the resulting event table is called as the model, which is DeliveryEvent in this example. But I would rather have it being named ep_delivery_event to be in accordance with our conventions. How can I achieve this? -
How to use multiple database connections in Django TestCase
I'm writing a testcase to reproduce deadlock in my service. After I use multiprocessing to create a two thread, I found they use the same database connection. So I can't reproduce the deadlock scenario in testcase. How do i resolve this issue? My code is as belows: @transaction.atomic() def process_1(): change = Change.objects.select_for_update().get(id="1") time.sleep(5) change = Change.objects.select_for_update().get(id="2") @transaction.atomic() def process_2(): change = Change.objects.select_for_update().get(id="2") time.sleep(5) change = Change.objects.select_for_update().get(id="1") p1 = Process(target=process_1) p2 = Process(target=process_2) p1.start() p2.start() p1.join() p2.join() self.assertEqual(p1.exitcode, 0) self.assertEqual(p2.exitcode, 0) -
Unable to Import 'celery' When Running pylint, but Django Runs Fine
I am working on a Django project and using uv as the package manager. My dependencies are managed in pyproject.toml, and I have the following setup: pyproject.toml (Relevant Parts) [project] name = "port-backend" version = "0.1.0" description = "Backend service for port.az" readme = "README.md" requires-python = ">=3.12" dependencies = [ "celery>=5.4.0", "django==4.2", "djangorestframework>=3.15.2", "djangorestframework-simplejwt>=5.5.0", "drf-spectacular>=0.28.0", ] [dependency-groups] dev = [ "pylint>=2.0.0", ] [tool.pylint.MASTER] ignore-paths = ['.venv/'] disable = [ 'C0415', # Import outside toplevel 'E0401', # Import error ] Steps Taken I ran uv sync, which created a new .venv and installed dependencies. VS Code detected the new environment and asked if I wanted to use it. I selected "Yes" and ensured the virtual environment was activated. Running uv run manage.py runserver works without issues, meaning Django and Celery are installed correctly. However, running uv run pylint . gives these errors: ************* Module manage manage.py:12:8: C0415: Import outside toplevel (django.core.management.execute_from_command_line) (import-outside-toplevel) ************* Module config.celery_app config/celery_app.py:3:0: E0401: Unable to import 'celery' (import-error) What I Have Tried Verified that Celery is installed in the .venv by running uv pip list, and celery is present. Checked that the .venv is activated in VS Code (terminal shows (port-backend) ➜ port_backend). Tried running uv … -
TemplateSyntaxError : Could not parse the remainder
Using easy-thumbnails package. Getting the error for the template file below. Cant seem to figure out what the syntax issue is. i.image is of type ImageFileField **Could not parse the remainder: ' i.image 320x260' from 'thumbnail i.image 320x260' ** for i in image_page.object_list %} <div class="col-6 mb-4 grid-item" style="display: none;"> Image thumbnail for gallery --> <div> <img class="img img-responsive" src= if i.image.thumbnail != null %} i.image.thumbnail }} else %} thumbnail i.image 320x260 }} endif %} " alt="{{ lot.product.title }}" data-toggle="modal" data-target="#lightboxModal" data-image-url="{{ i.image.url }}" data-pk="{{ i.pk }}" style="cursor: pointer;"> comment %} object-fit: contain; background-color: #f5f5f5; {% endcomment %} </div> </div> endfor %} Trying to conditionally render image thumbnail if already available in object or generate and save it if the thumbnail is not available. -
/bin/bash: line 1: gunicorn: command not found in railway
I am trying to host the Django backend of my website on railway, however when I try and deploy the server, I get: /bin/bash: line 1: gunicorn: command not found error in logs I've followed all the steps of creating a requirements.txt file, and a Procfile, but I still get the same error. -
How to design a Django database schema for tracking user-item interactions (with quantities) to enable analytics and reporting?"
I'm building a Django web app to manage item stock, where authenticated users can "take" items from inventory (I'm not using djangos authentication system, is more like the user enters a code and the app checks in SQL Server if exists then saves the session info). I need to store user interactions to later analyze and visualize data such as: Recent items taken Most popular items User-specific activity Date-filtered interactions Total quantities taken per item Full interaction history, etc. Im thinking each interaction should record: User who performed the action Items taken (multiple items per interaction) Quantity taken per item Timestamp The current structure I have is Users and Items Users (Django's built-in User model) Items (Model with fields like name, stock_quantity, etc.) -
Other users cannot connect to the server on the websocket
I have a server on AWS EC2 with port 8001 open with a websocket application. The application itself is written in Django Channels and uses a daphne server. The problem is that I myself can connect to the websocket server, but other users do not have such an opportunity for some reason The script I'm using to connect const socket = new WebSocket("ws://54.145.126.99:8001/ws/chat/first_user=19628&second_user=19629", ["Bearer", token]); socket.onopen = function () { console.log("✅ connected to WebSocket server"); }; local application use http://127.0.0.1:5173/, application that use frontend dev also use http://localhost:5173/ and runs on React. So, i don`t which info i need to provide that you can understand problem, becouse i have no idea where that error could be. If you need some information, write i provide all. -
How to parse api request to defined model?
I'm new with python, I'm trying to parse api request to a defined model, so how to fix below code? class PersonSerializer(serializers.Serializer): name = serializers.CharField() class APIJustTest(APIView): parser_classes = (JSONParser,) @swagger_auto_schema(request_body=PersonSerializer) def post(self, request, *args, **krgs): serializer = PersonSerializer(data=request.data) serializer.is_valid() nameOK = serializer['name'].value #dictionary works but I prefer defined model nameError = serializer.name #this is defined model but will cause server error return JsonResponse({}) -
Cannot assign "": "" must be a "User" instance
I'm making a project using the Django framework and is creating a website and is encountering this error: Cannot assign "<User: >": "Booking.teacher" must be a "User" instance. this is my models.py for the booking: class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) teacher = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'role': 'teacher'}) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() purpose = models.CharField(max_length=255, blank=True, null=True) class Meta: unique_together = ('room', 'date', 'start_time', 'end_time') def __str__(self): return f"{self.room.name} - {self.date} ({self.start_time} to {self.end_time})" this is my forms.py: class BookingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['teacher'].queryset = User.objects.filter(groups__name='teacher') # Filter teachers class Meta: model = Booking fields = ['room', 'date', 'start_time', 'end_time', 'teacher'] widgets = { 'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'start_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), # Updated to start_time 'end_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), # Added end_time 'room': forms.TextInput(attrs={'class': 'form-control'}), 'teacher': forms.Select(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super().clean() room = cleaned_data.get('room') date = cleaned_data.get('date') start_time = cleaned_data.get('start_time') end_time = cleaned_data.get('end_time') # Check for booking conflicts if Booking.objects.filter(room=room, date=date, start_time=start_time, end_time=end_time).exists(): raise ValidationError('This room is already booked for the selected date and time.') return cleaned_data and this is my views: def booking_calendar(request): rooms = Room.objects.all() # Fetch all rooms for the dropdown bookings = … -
Django template nested for loop from 2 different lists
I have 2 lists (if that is what django calls them) containg an id and a key/value pair e.g. [{'id': x, 'string': 'string'}] one list assigned to variable 'periods' the other assigned to 'paydates'. I am trying to loop through each list and display the value from each in an HTML element, using DTL. I have the DTL in the HTML page {% for ... in ... %} one inside the other. The outer for loop from list 'periods' is working correctly, the inner for loop from list 'paydates' is not displaying anything at all, it doesn't throw an error either. The blue date in the pic is from the 'periods' list and is working correctly, the date from the 'paydates' list is supposed to show underneath 'Pay Date'. I cannot separate the for loop code because of the way i want my html page displayed. I am not sure what options I have to rectify the issue. My code follows: home.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://unpkg.com/@tailwindcss/browser@4"></script> <link rel="stylesheet" href="{% static 'appmain/style.css' %}" /> <title>Payslip Data</title> </head> <body> <div class="container mx-auto my-10 border rounded-2xl border-4 border-purple-200 … -
Adding HTTPS to django app on VM(Windows OS) Production level
We are developing react native app with django as a backend. We deployed django on VM(which we bought it has Window OS) and there git pulled and running django server by just uvicorn backend.asgi:application --host 0.0.0.0 --port 8000, we want to add https in it how can we do it? we don't have a domain just public IP address, please reply if u have helpful information -
run one time for Django model calculated property
class Company_Car(models.Model): @property def days_left(self): print("RUNNED PROPERTY") if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date(): return (self.date_valid - datetime.datetime.now().date()).days added = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) date_valid = models.DateField(null=True, blank=True) Each time when i ask this property for same record it executes and it's not good My goal - property should run only once and return calculated data How it can done? -
Django: How to dynamically update stock quantity when selecting a product variation?
I am working on an e-commerce project where a product has multiple variations (like different colors, sizes, etc.), and each variation has its own stock. When a user selects a variation, I want to update the displayed stock dynamically, but it is not working correctly. Here’s my ProductStock model: class ProductStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="stocks") variation = models.ForeignKey(Variation, on_delete=models.CASCADE, blank=True, null=True) uploaded_stock_quantity = models.PositiveIntegerField(default=0) stock_quantity = models.PositiveIntegerField(default=0) reserved_stock = models.PositiveIntegerField(default=0) # For pending orders def available_stock(self): return self.stock_quantity - self.reserved_stock In my HTML template, I display variations as radio buttons: {% for v in variations %} <div class="variation__radio"> <input type="radio" id="variation_{{ v.id }}" name="variation" onclick="updateStock(this);" value="{{ v.id }}"> <label for="variation_{{ v.id }}">{{ v.name }}</label> </div> {% endfor %} <div class="stock-info"> <span id="uploaded-stock">-</span> in stock, <span id="remaining-stock">-</span> left </div> And my JavaScript function to update stock dynamically: function updateStock(element) { var variationId = element.value; var stockData = JSON.parse('{{ size_stock_data|safe }}'); // Pass stock data if (stockData[variationId]) { document.getElementById("uploaded-stock").textContent = stockData[variationId].uploaded_stock_quantity; document.getElementById("remaining-stock").textContent = stockData[variationId].stock_quantity; } else { document.getElementById("uploaded-stock").textContent = "-"; document.getElementById("remaining-stock").textContent = "-"; } } Issue The stock does not update when selecting a variation. Sometimes, it shows incorrect values or does not change at all. -
Is there any way to serve a Django application using preload, ASGI, and SO_REUSEPORT?
I can't find a way to serve our large Django application using all three of preload, ASGI, and SO_REUSEPORT. Without preload and fork we use much more memory (gigabytes). Without ASGI we can't serve websockets (and starting another server just for websockets would violate our memory constraints). Without SO_REUSEPORT we can run multiple preloaded/forked workers but traffic biases heavily (70%) to one worker, negating much of the benefit. We currently use gunicorn + uvicorn workers to achieve preload + ASGI. Gunicorn has an unreleased reuse_port mode that doesn't seem to do anything when using gunicorn + uvicorn. We looked at using granian or uvicorn itself as the process manager, but neither support preload/fork and so won't work due to our memory constraints. -
Should I Serve a React Build with Django or Use a Node.js Server if I am using Websockets with Django Channels?
I have a React application that I need to deploy, and I am considering two options for serving the production build: 1. Serving the React build directly with Django (e.g., using WhiteNoise or serving it as static files). 2. Using a Node.js server (such as Express) to serve the React build separately. I am having a websocket server in django channels using asgi. But I have build a react app in using the react. As the SSR is better in performance I was wondering if whether I can server my react build with django or not. Which approach is generally recommended, and what are the pros and cons of each? -
how to pass pk value in the forms and correctly call view.py method , showing a confirmation modal in django
The problem is that i dont see any print or log messages in my views.py , which made me to a conclusion that that method is not method is not being called. What i want to is to cancel subscription of a customer via button and show modal for confirmation. View.py : @login_required def cancel_subscription(request, pk): print("came to cancel sub") if request.method == 'POST': print("came to cancel sub") subscription = get_object_or_404(Subscription, pk=pk) subscription.status = 'expired' subscription.save() messages.success(request, 'Subscription cancelled successfully.') return redirect('customer_detail', pk=subscription.customer.pk) else: messages.error(request, 'Invalid request method.') return redirect('customer_list') customer_detail.html {% for subscription in subscriptions %} <button onclick="confirmCancelSubscription('{{ subscription.id }}')" class="flex items-center px-5 h-11 rounded-lg bg-error text-error-content hover:bg-error/90 transition-colors font-medium shadow-sm"> <svg class="h-5 w-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> <span>Cancel Subscription</span> </button> {% endfor %} <script> function confirmCancelSubscription(subscriptionId) { document.getElementById('cancelSubscriiptionModal').classList.remove('hidden'); const form = document.getElementById('cancelSubscriiptionModal'); form.action = "/cancel_subscription/" + subscriptionId + "/"; console.log(subscriptionId); } function closeModal() { document.getElementById('cancelSubscriiptionModal').classList.add('hidden'); } </script> my form.html <div id="cancelSubscriiptionModal" class=" hidden fixed inset-0 bg-black/50 items-center justify-center z-50"> <div class="bg-base-100 rounded-lg shadow-xl border-2 border-base-300 w-full max-w-lg mx-4"> <div class="px-6 py-4 border flex flex-col justify-between items-center"> <form method="POST" class="flex flex-col gap-10" > {% csrf_token … -
Django models migration gets generated after managed set to False
In my django project, the models Form, FormSubmission, CmsEvent are in a postgres database and the models CmsEventOrder, CmsEventPayment are in another postgres database. When I makemigrations, the migrations is created for all the models, while it should only be created for CmsEventOrder and CmsEventPayment Now the models CmsEventOrder and CmsEventPayment have a foreign key to the other 3 models. But the other 3 models have managed false, now do I reference them? Is the migrations getting generated because of the foreign keys? This is my view class CreateOrderView(APIView): def post(self, request): try: # Extract data from request amount = int(request.data.get('amount', 0)) * \ 100 # Convert to paise currency = request.data.get('currency', 'INR') receipt_id = "receipt_id_" + ''.join(random.choices( string.ascii_letters + string.digits, k=12)) notes = request.data.get('notes', {}) event_id = request.data.get('event_id') form_submission_id = request.data.get('form_submission_id') if amount <= 0: return Response({"error": "Amount must be greater than zero."}, status=status.HTTP_400_BAD_REQUEST) # Validate event and form submission event = get_object_or_404(CmsEvent, id=event_id) form_submission = get_object_or_404( FormSubmission, id=form_submission_id) # Initialize Razorpay client client = get_razorpay_client() # Create an order order_data = { 'amount': amount, 'currency': currency, 'receipt': receipt_id, 'notes': notes } order = client.order.create(order_data) # Save order to database CmsEventOrder.objects.create( order_id=order['id'], receipt_id=receipt_id, # Convert back to original currency … -
HTTP FAILED: java.net.ConnectException: Failed to connect to /127.0.0.1:8000
I am developing an android app in Kotlin and trying to make a request to my local Django server but getting this error. The local server is launched on IP and port 127.0.0.1:8000 and I specified in my android application the base url - http://127.0.0.1:8000/api, but I getting this error. I tried running it on both an emulator and a physical Android device, but I get the same result in both cases. I checked similar questions on StackOverflow and they suggest the following solutions: Find out the IP-address and enter it in the link, I found out my IP-address (for example 192.168.0.102) and used it instead of 127.0.0.1. Start local server via 0.0.0.0:8000. Add to ALLOWED_HOSTS IP-address of your PC in setting.py. Use IP address 10.0.2.2 for android emulator. If you have a Firewall active, add an exception for port 8000. Even though I have Firewall disabled, I still added an exception for port 8000. Started the server via IP address 192.168.0.102:8000. But when I tried all this, I got the following result: 1. <-- HTTP FAILED: java.net.ConnectException: Failed to connect to /192.168.0.102:80 Same result as number 1. Same result as number 1. <-- HTTP FAILED: java.net.ConnectException: Failed to connect … -
Wagtail one-to-one object hierarchy with enum type field
I have a wagtail site and I want to create an object hierarchy in a one-to-one matter, but with multiple options. Basically, I want that the database setup look slike this: CREATE TABLE products ( id PRIMARY KEY, product_type VARCHAR(10) CHECK (product_type IN ('BOOK', 'SHIRT', ...)), product_name VARCHAR(255), product_description TEXT, ... ); CREATE TABLE product_shirts ( id PRIMARY KEY, product_id integer REFERENCES products (id), size varchar(255), ... ); CREATE TABLE product_books ( id PRIMARY KEY, product_id integer REFERENCES products (id), author varchar(255), ... ); It is pretty straigt forward to create a regular one-to-one relationship with setting ParentalKey in the derived model. However, I want to also have an enum-type field in the parent model to check which product type we have, so that I can do something like that in my ProductsView: if object.product_type == 'SHIRT': # display additional shirt attributes elif object.product_type == 'BOOK': # display book attributes else: # unknown type, should not happen I know, that with a one-to-one relationship in wagtail I could just simply call product.shirtwhich would raise an exception, if the product is not a shirt. But it seems very cumbersome to have nested try-catch blocks if I have many different product types... … -
Azure AD Authentication with Django on AWS ALB: Redirect URI problem
I am trying to integrate Microsoft authentication with my Django app using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI. I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added https://myhost/oauth2/callback to the Web Redirect URLs as instructed. When attempting to authenticate, I receive the following error message with http URI instead of https: > AADSTS50011: The redirect URI 'http://myhost/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '944fce1cxxxx-xxx-xxxx-4f2abba56fb6'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this. I have created a record for the host in route53 and configured my ALB with ACM certificate. I am using below settings file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') DEBUG = False SITE_ID = 1 ALLOWED_HOSTS = ['myhost'] CSRF_TRUSTED_ORIGINS = ['myhost'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'workspaces', 'django_auth_adfs', 'django_extensions', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", … -
Stock Quantity Not Updating on Size Selection in Django Template with JavaScript
Problem Description: I'm working on a Django project where a product can have multiple size variants, and each size has its own stock quantity. I want to display the stock information dynamically when a user selects a size using JavaScript. However, the stock information is not updating as expected. It always shows undefined in stock or Only undefined left, even though I can see the correct stock data in the browser console. Models: class Size(models.Model): name = models.CharField(max_length=50) class Product(models.Model): title = models.CharField(max_length=255) class ProductStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="stocks") size = models.ForeignKey(Size, on_delete=models.CASCADE, blank=True, null=True) uploded_stock_quantity = models.PositiveIntegerField(default=0) stock_quantity = models.PositiveIntegerField(default=0) reserved_stock = models.PositiveIntegerField(default=0) def available_stock(self): return self.stock_quantity - self.reserved_stock Views: from django.shortcuts import render, get_object_or_404 def product_detail_view(request, pid): product = get_object_or_404(Product, pid=pid) sizes = product.size.filter(product=product) product_stocks = ProductStock.objects.filter(product=product) size_stock_data = { str(stock.size.id): { 'stock_quantity': stock.stock_quantity, 'uploaded_stock_quantity': stock.uploded_stock_quantity } for stock in product_stocks } return render(request, 'core/product_detail.html', { 'product': product, 'sizes': sizes, 'size_stock_data': size_stock_data }) Template: {{ size_stock_data|safe|json_script:"size-stock-data" }} <div class="u-s-m-b-15"> <div class="pd-detail__inline"> <span class="pd-detail__stock" id="uploaded-stock">-</span> <span class="pd-detail__left" id="remaining-stock">-</span> </div> </div> {% if sizes %} <div class="u-s-m-b-15"> <span class="pd-detail__label u-s-m-b-8">Size:</span> <div class="pd-detail__size"> {% for s in sizes %} <div class="size__radio"> <input type="radio" id="size_{{ s.id }}" name="size" value="{{ s.id }}" … -
How to style a Django crispy-form label
I'm developing a small project using Django v5 and Bootstrap v5. At this stage I'm just playing around with the registration and login pages but I'd like to style the form using crispy-form and the crispy FormHelper. I can change the displayed label but (so far) I've been unable to make the label bold and/or underlined to show that it is a required field (rather than using crispy's asterisk). For what it is worth here is my forms.py file: from django import forms from django.contrib.auth import get_user_model from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Field, Layout class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'autofocus': 'autofocus'})) password = forms.CharField(widget = forms.PasswordInput) class UserRegistrationForm(forms.ModelForm): password = forms.CharField( label = 'Password', widget = forms.PasswordInput ) password2 = forms.CharField( label = 'Repeat password', widget = forms.PasswordInput ) class Meta: model = get_user_model() fields = ['username','email','first_name','last_name'] widgets = { "username": forms.TextInput(attrs={'autofocus': 'autofocus'}), } def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError("Passwords don't match!") return cd['password2'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['username'].label= "User Name" self.fields['username'].help_text= "This will be your Login ID and must be unique" #self.helper.layout = Layout( #Field('username', label='User Name - Doug', css_class="fs-2") #) self.helper.add_input(Submit('submit', 'Register')) Note - the commented …