Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the downsides of default ordering by PK in Django?
Django models now support default ordering, via Meta.ordering. What are the downsides to putting ordering = ["pk"] on my base model? In particular, I'm curious about the performance impact. The Django docs have a vague warning that this can hurt performance: Ordering is not free; each field to order by is an operation the database must perform. If a model has a default ordering (Meta.ordering) and you don’t need it, remove it on a QuerySet by calling order_by() with no parameters. But is ordering by the primary key actually expensive if I'm using Postgres as my database? -
why my EC2 instance is not recognizing my app?
im new in AWS and i tried migrating my files in EC2 and i see this error, is it a problem in my structure? I would really appreciate any help since im working in my portfolio and i cant seem to host it correctly :( my repo: "https://github.com/theowla/Portfolio_TW.git" (venv) ubuntu@ip-172-31-37-85:~/Portfolio_TW/portfolio$ python manage.py migrate Traceback (most recent call last): File "/home/ubuntu/Portfolio_TW/portfolio/manage.py", line 22, in <module> main() File "/home/ubuntu/Portfolio_TW/portfolio/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project' i tried migrating my files after i changed the folder name and it now doesnt find my app -
Django DRF, Cannot reproduce POST request using APIClient and APITestCase, payload fields are removed
I have the following setup in Django DRF: class TagSerializer(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(required=True) style = serializers.JSONField(read_only=True) class TagCreationMixin: def create(self, validated_data): tags = validated_data.pop("tags", []) failure_mode = self.Meta.model.objects.create(**validated_data) for tag in tags: current_tag, _ = models.Tag.objects.get_or_create(**tag) failure_mode.tags.add(current_tag) return failure_mode class ItemSerializer(TagCreationMixin, serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) class Meta: model = models.Item fields = "__all__" And I want to automatize tests using APIClient and APITestCase. I have the following test defined: class TestAPIMissingTags(APITestCase): fixtures = [ "core/fixtures/users.yaml" ] payload = { "name": "test", "tags": [{"name": "test"}, {"name": "critical"}], } def setUp(self): self.user = models.CustomUser.objects.get(username="jlandercy") self.client = APIClient() self.client.force_authenticate(user=self.user) def test_complete_payload_is_sent(self): response = self.client.post("/api/core/item/", data=self.payload) print(response) print(response.json()) Which returns a 201 but without any tags, it seems they are popped from the initial payload: <Response status_code=201, "application/json"> {'id': 'f3cd6bbb-239f-4f47-9b2d-f648ead76bdd', 'tags': [], 'name': 'test'} Anyway when I challenge Swagger with the same endoint and payload it works as expected: { "id": "6d05c2e3-fce3-420d-bef9-4bccd28062f7", "tags": [ { "id": "fa70c875-818b-4ca2-9417-4209fd377453", "name": "test", "style": { "background-color": "#cc7a13" } }, { "id": "9fd59657-4242-432f-b165-1ed0a67546e3", "name": "critical", "style": { "background-color": "#bf8100" } } ], "name": "test" } Why cannot I reproduce the same behavior than Swagger using the APIClient. -
VS Code python extension seeing some not all Django class
Simple problem: the Python extension of VS Code is not seeing a Django class, while all other classes in same file are presented. Restarting, disabling/enabling, switch to pre-release for the extension doesn't change anything. Confirmed it was the extension as disabling it removes all import objects. AdminUserCreationForm is not being detected while UserCreationForm and other classes are visible. If I visit the source file by CTRL+click I can clearly see the class there: I've tried clearing a few VS Code caches (under AppData\Roaming\Code) to no avail. -
Django DRF, create an Item with associated tags whether they exist or not
I have the following create function for ItemSerializer class. It aims to create new Item with tags, creating tags on the fly if they does not exist or getting them if they exist. def create(self, validated_data): tags = validated_data.pop("tags", []) item= models.Item.objects.create(**validated_data) for tag in tags: current_tag, success = models.Tag.objects.get_or_create(**tag) item.tags.add(current_tag) return item Anyway when I perform a POST on the Item with already existing tag: { "tags": [{"name": "My Tag"}], "name": "My Item" } I get the following DRF 400 answer: { "tags": [ { "name": [ "tag with this name already exists." ] } ] } It seems in this case my create function is skipped and Django DRF tries to create the tag anyway. -
Django manage command set stdout and stderr
Is there a way to set stdout and stderr from base_stealth_options in BaseCommand when running the django command? I can't find any documentation about how to use those options. For example, I would like to set stdout and stderr to a logger info and error when running python manage.py foo. Code reference: https://github.com/django/django/blob/stable/5.2.x/django/core/management/base.py#L269 This is my attempt at making my own manage_custom_logging.py. I am wondering if there is a better way to do this since base_stealth_options exists. # manage_custom_logging.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import traceback import logging logger = logging.getLogger('manage_custom_logging') class StreamToLogger(object): def __init__(self, logfct): self.logfct = logfct def write(self, buf): for line in buf.rstrip().splitlines(): self.logfct(line.rstrip()) def flush(self): pass def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " 'available on your PYTHONPATH environment variable? Did you ' 'forget to activate a virtual environment?' ) from exc try: sys.stdout = StreamToLogger(logging.info) sys.stderr = StreamToLogger(logging.error) execute_from_command_line(sys.argv) except Exception: logger.error(traceback.format_exc()) if __name__ == '__main__': main() -
Where to set up subdomain routing? Front-end (React) or Django (Backend)?
I'm currently building a multi-tenant web application using Django and React. Right now, each user's page is available at a URL like https://mywebsite.com/. However, I want to change this so that each user has their own subdomain, for example: https://.mywebsite.com. My setup is as follows: I'm using React for the frontend and Django (with Django REST Framework) for the backend. Both are running on the same server. I’m serving the React build/ folder directly through Django by connecting it in the Django urls.py file. What I want to achieve is true subdomain-based routing so that each user or tenant can have their own subdomain. I’m not sure exactly what changes are needed to make this work, especially across the different layers of the stack. Specifically, I’m looking to understand what needs to be done at the DNS or Nginx/server configuration level, what changes I need to make in Django to detect and handle subdomains, and whether any updates are needed on the React side. I’m also wondering whether there’s a way to test this kind of subdomain setup locally during development (like on localhost). Finally, I'd like to know how to extract the subdomain (which would be the username or … -
My VM not connecting to MySQL – 2002 error
I’m currently experiencing issues with my virtual machine named "monitoramentoati". When trying to access my application through the domain https://monitoramentoati.camf.org.br/admin/login/, I encounter the following error from Django: "OperationalError at /admin/login/ (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)")" The full traceback points to an issue with the Django application being unable to connect to the local MySQL server via socket. However, when I check the MariaDB service inside the VM, it shows as active (running) and the socket being used is: "/run/mysqld/mysqld.sock" This differs from the path Django is trying to use (/var/run/mysqld/mysqld.sock), which may indicate a misconfiguration or a linking issue in the filesystem. Additionally, I’m seeing logs like the following in the system log viewer (Cloud Logging): "May 14 15:43:56 monitoramento-ati gunicorn[915]: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)")" I was wondering if you could help me with this problem. What should I do? I tried to update the mysql, django and everything that I can and did't work. -
Creating TabularInline in Django Admin View for inherited Many2Many relation
I have a Tag Model and Mixin that is used for adding tags to entities whenever it is needed. class Tag(models.Model): name = models.CharField(max_length=64, unique=True) class TagMixin(models.Model): class Meta: abstract = True tags = models.ManyToManyField(Tag, blank=True) To create new entities it works well, it implicitly creates the correspondence table for the many to many relation: class Item(TagMixin): name = models.CharField(max_length=64) But what if I want create an admin view on Item where tag is a TabularInline input ? How should I fill the configuration: class ItemTagInline(admin.TabularInline): model = ? @admin.register(models.Item) class ItemAdmin(admin.ModelAdmin): list_display = ("id", "name") inlines = [ItemTagInline] -
Airwallex Payment Link not redirecting to custom redirect_url after successful payment
I'm integrating Airwallex payment links into my web application. After a successful payment, instead of being redirected to my custom success URL (e.g., https://example.com/paymentsuccess), users are taken to the Airwallex default success page. Here's how I'm creating the payment link What I've Checked: The URLs are correct and publicly accessible. There are no obvious network or HTTPS issues. I confirmed that the payment completes successfully — it’s just the redirection that fails. Tech Stack: Backend: Python/Django Airwallex SDK/API Environment: Test mode What I'm Looking For: Is there any additional setting or flag required when creating the Airwallex payment link to enforce redirection? Does Airwallex override redirect_url in certain scenarios? Is there a webhook/setting in the dashboard I need to configure? -
NEAR API python
getting error when setting up py-near for a django project getting error when downloading py-near using pip AttributeError: module 'configparser' has no attribute 'SafeConfigParser'. Did you mean: 'RawConfigParser'? pip install py-near -
What is the best and production-safe way to handle long process them efficiently in Django, ideally with parallel processing?
I'm working on a Django app where users upload large .txt files that need to be parsed and stored in a PostgreSQL database. The files can contain hundreds of thousands of lines, and processing them can take a long time. Currently, I'm using threading.Thread with an in-memory tasks_registry to process the file and stream task status. It works in development, but I now realize this approach is not safe in production, especially with Gunicorn and multiple workers. upload data / Process the file in parallel for better performance Send a response to the frontend after the upload completes, while the processing continues in the background Safely handle this under Gunicorn or another WSGI server Any recommendations for architecture or proven patterns would be very helpful? -
Getting this error had repository from git and python virtual environment is activated just getting problem to activate from source env/bin/activate
WARNINGS: ?: (staticfiles.W004) The directory 'C:\Ansh\ecom\django_project_boilerplate\static_files' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run 'python manage.py migrate' to apply them. May 15, 2025 - 23:00:06 Django version 5.2.1, using settings 'demo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead. For more information on production servers see: https://docs.djangoproject.com/en/5.2/howto/deployment/ getting this error -
Django view doesn't save form changes
Django 5.2, python 3.12.5 . I'm using in-built user model and no errors appear when I press the submit button. I created a view based on UpdateView and use the built-in UserChangeForm. The form actually returns 200 response code. I suspect something is wrong with how the form is bound or saved, but I see no errors or warnings. Urls are okay. My other login/register forms work well. views.py from django.views import generic from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User class ProfileView(generic.edit.UpdateView, LoginRequiredMixin): template_name = 'users/profile.html' form_class = UserChangeForm success_url = '/profile/' model = User def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Profile | Jotter' return context def form_valid(self, form): form.save() return super().form_valid(form) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['instance'] = self.request.user return kwargs def get_object(self): return self.request.user profile.html {% extends "base.html" %} {% block content %} <main class="py-5"> <div class="container"> <div class="row"> <form action="" method="post" class="col-md-6 mx-auto"> {% csrf_token %} <h2 class="mb-5">Account details</h2> <div class="row mb-4"> <div class="col-md-4 mx-2"> <label for="username_label" class="form-label">Username</label> <input type="text" class="form-control" style="background: #dfdfdf;" id="username_label" name="username" value="{{form.username.value}}" readonly> </div> </div> <div class="row mb-5"> <div class="col-md-4 mx-2"> <label for="first_name_label" class="form-label">First name</label> <input type="text" class="form-control" id="first_name_label" name="first_name" … -
Post data into database failed with form invalid message
#I can not send data to my db, please help me to check.# Here is the model Model: class f_groupe_user(models.Model): IDF_GROUPE_USER=models.AutoField(primary_key=True) LibELE_GROUPE= models.CharField(max_length=120) Soc_sigle = models.CharField(max_length=120) created_at=models.DateTimeField(auto_now_add=True) updated_at= models.DateTimeField(auto_now=True) UTIL_CREATION= models.CharField(max_length=120) UTIL_MODIF= models.CharField(max_length=120) def __str__(self): return self.LibELE_GROUPE Here is the form class f_groupe_userForm(forms.ModelForm): class Meta: def __init__(self, *args, **kwargs): super(f_groupe_userForm, self).__init__(*args, **kwargs) model = f_groupe_user fields = ['LibELE_GROUPE', 'UTIL_CREATION', 'UTIL_MODIF','Soc_sigle'] labels = {'LibELE_GROUPE': 'Nom*', 'created_at': 'Date de création', 'updated_at': 'Date de modification', 'UTIL_CREATION': 'UTIL CREATION', 'UTIL_MODIF': 'UTIL MODIF', 'Soc_sigle':',Societe'} widgets={ 'name' : forms.TextInput(attrs={'class':'form-control'}), } help_texts = { "LibELE_GROUPE": _("Donner le nom du groupe utilisateur"), } error_messages = { "name": { "max_length": _("Ce nom du groupe est trop long."), }, } Here is the views def Insert_group(request): print(f" La Request method est : {request.method}") sEtat = "crea" if request.method == 'POST': print('Je rentre dans group Insert_group avec POST')) form = f_groupe_userForm() form.LibELE_GROUPE = request.POST.get("LibELE_GROUPE") form.updated_at = timezone.now() form.created_at = timezone.now() form.UTIL_CREATION = settings.WCURUSER form.UTIL_MODIF = settings.WCURUSER form.Soc_sigle = settings.WSOCGEN data = { "UTIL_CREATION": settings.WCURUSER, "UTIL_MODIF": settings.WCURUSER, "Soc_sigle" : settings.WSOCGEN, } print(f" La valeur de data est : {data}") form = f_groupe_userForm(request.POST, initial=data) print(request.method) if form.has_changed(): print("The following fields changed: %s" % ", ".join(form.changed_data)) if form.is_valid(): LibELE_GROUPE = form.cleaned_data['LibELE_GROUPE'] created_at = form.cleaned_data[ … -
Reverse for "not found." is not a valid view or function name error [closed]
I am working on my major project for software engineering in highschool and I keep coming up with this error when I run my Django project. I followed the tutorials set out by my teacher but I still don't know what's going on. This is the error message that keeps coming up. Reverse for "not found." is not a valid view or function name. This is my project urls.py file """ Software_Engineering_Major_Project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.urls import path,include import Dark_Library_store.Urls urlpatterns = [ path('',include('Dark_Library_store.Urls')), ] This is my app Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('store/', views.Store, name='store'), path('featured/', views.Featured, name='featured'), path('cart/', views.Cart, name='cart'), path('contact/', views.Contact, name='contact'), path('login/', views.Login, name='login'), path('sign_up/', views.Sign_up, name='sign_up'), ] This is my … -
django image cropping error : 'ImageField' object has no attribute 'image_field'
I am using Amazon S3 as File Storage. I tried to use django image chopping 1.7 to handle photo it works for showing image without django image chopping on website and I read official documentation cover_photo = models.ImageField(upload_to='package_inner_photos', null=True, blank=True) cover_photo_cropping = ImageRatioField('inner_photo',free_crop=True) {% if package.cover_photo %}style="background-image: linear-gradient(rgba(0,0,0,0.1), rgba(0,0,0,0.1)), url('{{ package.cover_photo.url }}');"{% endif %} it can show the photo but no cropping effect, of coz however {% load cropping %} {% if package.cover_photo %},url('{% cropped_thumbnail package "cover_photo" %}');"{% endif %} debug page show the error that 'ImageField' object has no attribute 'image_field' Django generated thumbnail file on Amazon S3 actually I double checked particular entries p = Package.objects.get(slug="ozen-reserve-bolifushi") print(p.inner_photo) print(p.cover_photo.name) print(p.cover_photo.url) it return the file name correctly I made Amazon S3 ACL almost public, I am not sure which part go wrong. Can anyone help please? -
Django Crispy Forms with Tailwind CSS 4.0: Unwanted downward caret appears within the form
I'm using: Django 5.2.1 Tailwind CSS 4.0 crispy-tailwind 1.0.3 django-crispy-forms 2.4 I am using the Tailwind template pack, which is defined in my settings.py. When I render my form in my template 'concert_form.html' using crispy-forms, a large upside-down caret symbol appears after one of the fields in the middle of the form. If I comment out crispy-forms, then the form renders properly. Using the developer tools, with crispy-forms active, I can see there is a new in the code with an svg definition. That is not present with crispy-forms inactive. The only CSS I'm using is what is generated from the tailwind --watch command. Is there any way I can control crispy-forms to prevent this from happening? Here are the relevant code sections: concert_form.html html {% extends "_base.html" %} {% load tailwind_filters %} ... <div class="bg-white rounded-lg shadow-lg p-6"> <form method="post" class="space-y-6"> {% csrf_token %} {% form|crispy %} <div class="flex justify-end space-x-3 pt-4"> ... the balance of the code, navigation buttons to 'Cancel' or 'Submit' the form models.py python from django.db import models from django.urls import reverse class ConcertForm(forms.ModelForm): name = models.CharField(max_length=100) date = models.DateField() time = models.TimeField() venue = models.ForeignKey(Venue, on_delete=models.CASCADE) conductor = models.ManyToManyField(Conductor, blank=True) guests = models.ManyToManyField(Guest, blank=True) … -
Stripe InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You passed an empty string for 'line_items[0][price]'. We assume empty values
I am trying to set a subscription service on my website using Django. models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) customer_id= models.CharField(max_length=255) subscription_id = models.CharField(max_length=225, unique=True) product_name = models.CharField(max_length=255) price = models.IntegerField() interval = models.CharField(max_length=50, default="month") start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) canceled_at = models.DateTimeField(null=True, blank=True) @property def is_active(self): if self.end_date: if now() < self.enddate: return True else: return False else: return True @property def tier(self): tier_mapping = { 'Basic Membership': 1, 'Premium Membership':2, 'Pro Membership':3, } tier = tier_mapping.get(self.product_name, None) return tier def __str__(self): return f"{self.user.username} - {self.product_name} Active: {self.is_active}" views.py from django.shortcuts import render, redirect, reverse import stripe from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY def subscription_view(request): subscription = { 'Basic Membership' :'price_1RNgLNIoFyCdZSrgu83irObA', 'premium' :'price_1RNgLvIoFyCdZSrg9j87OiP7', 'pro' :'price_1RNgMUIoFyCdZSrgEIxgO9HP', } if request.method == 'POST': if not request.user.is_authenticated: return redirect(f"{reverse('account_login')}?next={request.get_full_path()}") price_id = request.POST.get('price_id') checkout_session = stripe.checkout.Session.create( line_items=[ { 'price':price_id, 'quantity':1, }, ], payment_method_types=['card'], mode='subscription', success_url = request.build_absolute_uri(reverse("create_subscription")) + f'?session_id={{CHECKOUT_SESSION_ID}}', cancel_url=request.build_absolute_uri(f'{reverse("subscription")}'), customer_email=request.user.email, metadata={ 'user_id': request.user.id, } ) return redirect(checkout_session.url, code=303) return render(request, 'a_subscription/subscription.html', {'subscription' : subscription}) def create_subscription(request): #create subscription object in database return redirect('my_sub') def my_sub_view(request): return render(request, 'a_subscription/my-sub.html') Error message: InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You … -
How to send video(mp4) as a response
I need to know how i can send a video file as a response in django. React+Django this is my djanog code which is handling the request. u/csrf_exempt def get_video(request): view_logger.info("Fetching video") try: if not LOGS_FOLDER_PATH: view_logger.warning("LOGS FOLDER PATH not present") return HttpResponseNotFound("Logs folder path not set.") videos_path = os.path.join(LOGS_FOLDER_PATH, "videos") if not os.path.exists(videos_path): return HttpResponseNotFound("Videos folder does not exist.") videos_list = os.listdir(videos_path) if not videos_list: return HttpResponseNotFound("No videos found.") video_path = os.path.join(videos_path, videos_list[0]) view_logger.info(f"Video path:- {video_path}") video_response = FileResponse( open(video_path, 'rb'), ) view_logger.info(f"\n\n\n{video_response}") return video_response except Exception as error: view_logger.error(f"Error fetching terminal video. Error: {error}") return JsonResponse({'error': 'Internal server error'}, status=500) LOGS_FOLDER_PATH - I can't add this as static cuz I receive this during runtime. React Code:- import React from "react"; import "./CSS/VideoDisplay.css"; const VideoDisplay = ({ api_url_name }) => { return ( <div className="video-display-div"> <video width="100%" controls aria-label="video"> <source src={`${api_url_name}/api/dashboard/get-video/`} type="video/mp4" /> Your browser does not support the video tag. </video> </div> ); }; export default VideoDisplay; I tried returning the video as response using FileResponse but the video is not displaying the Frontend. -
Django ModelForm not prepopulating fields when updating instance – "This field is required" errors
I'm making a project in Django--UniTest. The idea is to let our university's faculty create and conduct online surprise tests on it. The issue I'm facing is with the update_test.html page which is not prepopulating the data. Here's the view function. @login_required def update_test(request, test_id): test = get_object_or_404(Test, id=test_id) questions = test.questions.all() print(test) print(test.name, test.course, test.batch, test.total_marks, test.total_questions, test.duration) if request.method == 'POST': form = testForm(request.POST, instance=test) print("Form Data:", request.POST) print("Form Errors:", form.errors) print(form.initial) # Check if the form is valid # and if the test ID matches the one in the URL if form.is_valid(): form.save() # Update questions and choices for question in questions: question_text = request.POST.get(f"question_{question.id}") question_marks = request.POST.get(f"question_marks_{question.id}") question.text = question_text question.marks = question_marks question.save() # Update choices for each question for choice in question.choices.all(): choice_text = request.POST.get(f"choice_{question.id}_{choice.id}") is_correct = request.POST.get(f"is_correct_{question.id}_{choice.id}") is not None choice.text = choice_text choice.is_correct = is_correct choice.save() return redirect('list_tests') else: form = testForm(instance=test) return render(request, 'update_test.html', {'form': form, 'test': test, 'questions': questions}) Output: Dummy | Computer Networking 2 | BCA | 3 marks | 2 questions Dummy Computer Networking 2 | CSE309 BCA | 2022-2025 | 4th sem | A 3 2 10:00:00 Form Data: <QueryDict: {'csrfmiddlewaretoken': ['7WtmPpjyY1Ww1cCRuRxEOpwKmESSSjVv8jXToOQ5PSb4MEU5tZXgA93tUwzkGTeU']}> Form Errors: <ul class="errorlist"><li>name<ul class="errorlist"><li>This … -
Is it possible to use DRF's datetime picker and include the UTC offset for timestamps in the response JSON?
I am trying to use the Web browsable API in Django Rest Framework. I have objects with timestamp data in this format, "2025-05-08T22:02:58.869000-07:00". But the required format for Django's datetime picker does not support UTC offset or the last three significant digits for microseconds as shown below: I can trim the input data to satisfy the datetime picker like this: class MillisecondDateTimeField(serializers.DateTimeField): def to_representation(self, value): return value.astimezone().strftime("%Y-%m-%dT%H:%M:%S") + ".{:03d}".format( int(value.microsecond / 1000) ) But then the UTC offset is also missing from the timestamp in the POST/PUT response. { ... "start_datetime": "2025-05-08T22:02:58.869", ... } How can I make the value for "start_datetime" appear as "2025-05-08T22:02:58.869000-07:00" in the JSON response from POST/PUT while also using "2025-05-08T22:02:58.869" in the datetime picker? I have been researching online and trying for days. -
How can I set a javascript const to a value in a form element that could be either a dropdown select or a checked radio button?
I have an html form in a django site that is used for both add and update. If the form is for a new entry, I want the field estimateType to be radio buttons with three choices, one of which is checked by default. If the form is for an edit to an existing entry, I want the form widget to change to a select dropdown with additional choices to pick from. In the javascript in the onchange event, I need to know what the value of the estimateType field is. I can get it to work for select, or radio input, but not both. For example, what I have right now is: const estimateType = document.querySelector(input[name=estimateType]:checked).value; That works for a radio button but not the select dropdown. How can I use the same const declaration but account for heterogeneous form input types? -
Django filter objects which JSONField value contains in another model's JSONField values LIST of same "key"
I'm not sure if the title of this post made you understand the problem but let me explain: I have models: class ItemCategory(models.Model): name = CharField() class Item(models.Model): brand = CharField() model = CharField() category = ForeignKey(ItemCategory) attributes = JSONField(default=dict) # e.g {"size": 1000, "power": 250} class StockItem(models.Model): item = ForeignKey(Item) stock = ForeignKey(Stock) quantity = PositiveIntegerField() This models represent some articles on stock. Now I want to implement functionality to allow user create "abstract container" where he can input data and monitor how many of "abstract containers" may be produced based on stock remainings. Example: class Container(models.Model): name = CharField() class ContainerItem(models.Model): container = models.ForeignKey(Container) item_category = models.ForeignKey(ItemCategory) attributes = models.JSONField(default=dict) quantity = models.PositiveIntegerField() To handle aggregation I build a view: class ContainerListView(ListView): model = models.Container def get_queryset(self): items_quantity_sq = models.Item.objects.filter( item_category=OuterRef('item_category'), attributes__contains=OuterRef('attributes'), ).values('item_category').annotate( total_quantity=Sum('stock_items__quantity') ).values('total_quantity') min_available_sq = models.ContainerItem.objects.filter( container_id=OuterRef('pk') ).annotate( available=Coalesce(Subquery(items_quantity_sq), Value(0)) ).order_by('available').values('available')[:1] base_qs = super().get_queryset().annotate( # Attach the minimum available quantity across all items potential=Subquery(min_available_sq) ).prefetch_related( Prefetch( "items", queryset=models.ContainerItem.objects.all() .annotate(available=Subquery(items_quantity_sq)) .order_by("available"), ) ) return base_qs.order_by("potential") It works until ContainerItem attributes field contains a single value: {"size": 1000} but I want to allow user to input multiple values ("size": [1000, 800]) to find all Item objects which attributes … -
How to create a form Django (names and elements) from a column of a DataFrame or QuerySet column.?
How can I create a form - even if it's not a Django form, but a regular one via input? So that the names and elements of the form fields are taken from a column of a DataFrame or QuerySet column. I would like the form fields not to be set initially, but to be the result of data processing - in the form of data from a column of a DataFrame or QuerySet column. The name of the form fields to fill in from the data in Views. Maybe send a list or a single DataFrame or QuerySet to the template via JINJA? from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) from django.shortcuts import render from .forms import InputForm # Create your views here. def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) <form action = "" method = "post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> How to create a form Django (names and elements of the form fields) from a column of a …