Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, I would like to narrow a choice using a form to another form
I am trying to use the result of a selection as input to another selection. I have been working on this for three weeks, and I cannot find a simple answer. Here are my models: from django.db import models # Create your models here. class School(models.Model): id = models.CharField(primary_key=True, max_length=10) school_name = models.CharField(max_length=80) def __str__(self): return(f"{self.id} {self.school_name}") return self.id class Meta: ordering = ['id'] indexes = [ models.Index(fields=['id', 'school_name']), ] class Courses(models.Model): id = models.CharField(primary_key=True, max_length=12) created_at = models.DateTimeField(auto_now_add=True) school = models.ForeignKey(School, on_delete=models.PROTECT, related_name='school') name = models.CharField(max_length=150, null=True, blank=True) cost = models.CharField(max_length=75, null=True, blank=True) class Meta: ordering = ['id'] indexes = [ models.Index(fields=['school']), models.Index(fields=['name', 'id'])] def __str__(self): return(f"{self.school} {self.name}") return self.name class Student(models.Model): course = models.ForeignKey(Courses, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) student_id = models.CharField(max_length=20, null=True, blank=True) class Meta: ordering = ['course'] indexes = [ models.Index(fields=['course']), ] And my views: def choose_school3(request): if request.user.is_authenticated: aschool = Courses.objects.all() form=SelectSchoolForm(request.POST) if request.method == "POST": if form.is_valid(): data = form.cleaned_data choice = data['school'] selected_school = Courses.objects.filter(school=choice).values() context = {'choice': choice} return render(request, 'add_student2b.html', context) context = {'form': form, 'aschool':aschool} return render(request, 'choose_school3.html', context) else: messages.success(request, "You Must Be Logged In To View Records!") return redirect('main') def add_student2b(request, choice): chosen_school = Courses.objects.filter(school=choice).values() form = AddStudentForm(request.POST) context … -
How to create restore password function with Django rest framework?
I have a Django Rest Framework app. And I try to create reset password function. But the problem I am facing is that some functions are not called by the Django Rest Framework. So I have a module accounts--> templates --> registration and then the html templates in it. Like: password_reset password_reset_confirm password_reseet_done password_reset_form And in the accounts module I have a views.py file: from django.shortcuts import render from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_str from django.contrib.auth.tokens import default_token_generator from rest_framework import generics from .serializers import ChangePasswordSerializer class PasswordResetConfirmView(generics.GenericAPIView): serializer_class = ChangePasswordSerializer def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): return render(request, 'registration/password_reset_confirm.html', {'validlink': True, 'user': user, 'uidb64': uidb64, 'token': token}) else: return render(request, 'registration/password_reset_confirm.html', {'validlink': False}) def post(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"message": "Password has been reset successfully."}, status=status.HTTP_200_OK) else: return Response({"error": "Invalid link."}, status=status.HTTP_400_BAD_REQUEST) And a serializers.py file: from django.utils.translation import gettext as _ from … -
Is there any option to get "to-many" relation objects while saving "parent" object?
I have three models class Parent(models.Model): name = models.CharField(blank=True, max_length=20) ... # other fields def _get_childs(self): first_childs = [f'{child.name}' for child in self.one_childs.all()] second_childs = [f'{child.name}' for child in self.two_childs.all()] return [first_childs + second_childs] @classmethod def get_config(cls) -> str: try: instance = cls.objects.get() except cls.DoesNotExist: return '' config = {} for child in instance._get_childs(): config[child] = { 'interval': 1000, ... # other fields } return json.dumps(config, indent=4) class OneChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='one_childs') ... # other fields class TwoChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='two_childs') ... # other fields I need to write get_config result to file ('/tmp/config' as example) on Parent save. everything works fine, but i get previous relations childs, not new. i tried to use it in post_save signal for Parent model, but it is does not help. there is a signal for example @receiver(post_save, sender=Parent) def update_config(sender, instance, **kwargs): config_json = instance.get_config() file_path = '/tmp/config.json' with open(file_path, 'w') as file: file.write(config_json) when I save Parent all values become valid except child.name's is there any option to achieve this? -
Deployment of containerized Reat Django app with nginx
I have an app: client in react. server in django. the app is containerized: backend-container and frontend-container as follows (docker-compose.yaml): version: '3.8' services: backend: build: context: ./backend dockerfile: Dockerfile args: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: backend container_name: backend-container ports: - "8000:8000" environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} frontend: build: context: ./frontend dockerfile: Dockerfile args: REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: frontend container_name: frontend-container ports: - "3000:3000" environment: NODE_ENV: production REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} and the app is hosted on an EC2 instance, deployed using github action: name: My workflow on: workflow_dispatch jobs: first-job: runs-on: self-hosted steps: - name: Checkout code uses: actions/checkout@v4 - name: Build the Docker backend image env: POSTGRES_USER: ${{ secrets.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }} SECRET_KEY: ${{ secrets.SECRET_KEY }} DEBUG: ${{ secrets.DEBUG }} CORS_ALLOWED_ORIGIN: ${{ secrets.CORS_ALLOWED_ORIGIN }} REACT_APP_ALLOWED_HOST: ${{ secrets.REACT_APP_ALLOWED_HOST }} run: | sudo docker-compose -p fullstack down sudo POSTGRES_USER=$POSTGRES_USER POSTGRES_PASSWORD=$POSTGRES_PASSWORD POSTGRES_HOST=$POSTGRES_HOST SECRET_KEY=$SECRET_KEY DEBUG=$DEBUG CORS_ALLOWED_ORIGIN=$CORS_ALLOWED_ORIGIN REACT_APP_ALLOWED_HOST=$REACT_APP_ALLOWED_HOST docker-compose -p fullstack up --build -d I can see the containers are running on my EC2 instance. I configured an nginx on the EC2 instance: server { listen 80; server_name _; location / … -
Review table for two different profile types in Django and PostgreSQL DB
I have a question how I should design this relational database. I have a main profile, which has 2 sub-profiles, which are weak entities. These sub-profiles represent counterparts of a business process, an Employee and an Employer. Given I want to have tables that are related to these sub-profiles, such as "Review" or "Job Posting" (Similar to LinkedIn), which approach would be the most suitable: Creating a separate table for each profile type, e.g., EmployerReview and EmployeeReview Creating a single unified table, which has fields to determine which sub-profile type is sending and receiving the data. e.g., Review sender models.ForeignKey(Profile...) receiver models.ForeignKey(Profile...) sender_type models.CharField(max_length=15, choices=PROFILE_TYPES) receiver_type models.CharField(max_length=15, choices=PROFILE_TYPES) My main concern is the performance issues, e.g., when wanting to query all EmployerProfiles and the related Reviews of that profile. Now, If I have understood correctly, in method 2. you would have to do filter query, which is obviously slower than select_related (Similar to SQL Join?). The gain would be more flexibility and simple complexity, but there would be performance loss. Which of these methods would be more standardized or optimized way for such a problem? I tried creating both of the solutions, and they both work, but I am not … -
SequenceField to share unique IDs across multiple tables and more
Hello Django community, I recently faced a case where I had to have multiple models/tables having unique IDs coming from the same postgresql sequence. I was amazed to see how difficult it is to this from Django and I couldn't find a nice package doing this neither. So I developed django-sequencefield to address this limitation.: https://github.com/quertenmont/django-sequencefield Cherry on the cake, django-sequencefield could also be used to generate uniqueId containing additional data. I showcase a model using an id that is composed of a date (2 bytes) and a unique sequence id (6 bytes). This is useful to cluster the table simultaneously by date and Id while guaranteeing unicity and avoiding the use of composed primary key (not supported by Django). I would like to have feedback on this work, so feel free to try and comment. Thank in advance Loïc -
Can't install Python Imaging Library "Pillow"
I have tried to install pillow library for my Django project it won't install. I have tried many times there are no specific answer for problem on internet. First Try Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> pip install pillow Terminal Output: Fatal error in launcher: Unable to create process using '"c:\users\samsung\desktop\lms\venv\scripts\python.exe" "C:\Users\Samsung\Desktop\lms-django\venv\Scripts\pip.exe" install pillow': The system cannot find the file specified. Second Try: Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> python3 -m pip install Terminal Output: The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:8 + python3 <<<< -m pip install + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I want to find a way to install the python pillow library. -
Django losing connection with Postrgres creating a tenant
Developing a Django project using django-tenants. In the moment of new user registration, the tenant has to be created on the host domain with address "project-url.ru/username/..." Here is view.py with registration def create_user_tenant(request): user = UserClass.objects.get(username=request.POST['username']) schema_name = f'{user.username}_schema' try: with transaction.atomic(): tenant = Tenant(schema_name=schema_name, user=user) tenant.save() logger.debug(f'Tenant {tenant} created') domain = Domain(domain=HOST_NAME, tenant=tenant, is_primary=True) domain.save() logger.debug(f'Domain {domain} created for tenant {tenant}') logger.info(f'Tenant for {user.username} was created.') except IntegrityError as e: logger.error(f'Error creating tenant or domain for user {user.username}: {e}') except Exception as e: logger.error(f'Unexpected error creating tenant or domain for user {user.username}: {e}') def registration(request): error_msg = '' with transaction.atomic(): if request.POST: logger.debug(f"Registration request") form = UserRegistrationForm(data=request.POST) if form.is_valid(): user = form.save() logger.debug(f"User {user.username} has been registered") create_user_tenant(request) return redirect('login') else: error_msg = form.error_messages logger.debug(f"Registration form is invalid. Error {error_msg}") context = { 'form': UserRegistrationForm(), 'error_msg': error_msg, } return render(request, 'users/registration.html', context) However, when saving the tenant tenant.save() I get an error: The connection 'username_schema' doesn't exist. At the same time, if I do the same via ./manage.py shell everything works correctly. DB settings in settings.py: DATABASES = { "default": { 'ENGINE': "django_tenants.postgresql_backend", ..... } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... ] Postgres runs … -
Serving Static Files with Nginx and Django in Docker
Despite seeing many similar issues in other threads, I've been unable to configure Nginx to serve static files from my Django project. Here are my two static variables in my settings.py: STATIC_URL = '/static/' STATIC_ROOT='/opt/django/portfolio/collectstatic' Here is my dockerfile to build project image: FROM python:3.11-slim WORKDIR opt/django/ COPY pyproject.toml . RUN python -m pip install . COPY ./portfolio/ ./portfolio/ WORKDIR portfolio/ RUN python manage.py collectstatic --noinput RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD ["gunicorn", "portfolio.wsgi:application", "--bind", "0.0.0.0:8000"] Here is the docker-compose.yml: services: web: build: context: . dockerfile: ./docker/Dockerfile_django container_name: webserver volumes: - static_data:/opt/django/portfolio/collectstatic expose: - "8000" ports: - "8000:8000" depends_on: - db networks: - docker_network db: image: postgres:15 container_name: db_postgres expose: - "5432" ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres networks: - docker_network nginx: image: nginx:latest container_name: nginx ports: - "80:80" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - static_data:/opt/django/portfolio/collectstatic depends_on: - web networks: - docker_network volumes: postgres_data: static_data: networks: docker_network: driver: bridge name: docker_network And finally, here is my nginx.conf: events {} http { server { listen 80; server_name localhost; location /static { alias /opt/django/portfolio/collectstatic; autoindex on; } # skip favicon.ico location /favicon.ico { access_log off; return 204; } location / { proxy_pass … -
Django date() doesn't translate uk and run month names
When I try to get localized datetime in a template using {{ enrolment.datetime_access_ends|date:"j E Y" }} I get 29 July 2025 (instead of expected 29 июля 2025). Localization works fine in all other places. I have this in my settings.py: LOCALE_PATHS = [BASE_DIR / "locale"] # type: ignore TIME_ZONE = "Europe/Kiev" USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGE_CODE = "ru-UA" LANGUAGES = [ ("ru", _("Russian")), ("uk", _("Ukrainian")), ] When I try to get month translation from shell, I get expected results: >>> activate("uk") >>> date(timezone.now(), "F") 'Серпень' >>> activate("ru") >>> date(timezone.now(), "F") 'Август' But when I try to do the same from inside of the view, for some reason it doesn't work: print(get_language()) print(date(timezone.now(), "F")) gives ru August in logs. And if I change language to any other then uk or ru activate("pt") it works fine: pt Agosto -
Django + Javascript - dynamic ModelForm generation issue
I have this code {% extends 'base.html' %} {% block content %} <form method='POST'> <script> function addMemberFnc() { document.getElementById("teamMemberDiv").innerHTML+={{ project_members_form }} } </script> {{ project_form }} <p id="demo" onclick="addMemberFnc()">Add member.</p> <div style="border-style: dotted" id="teamMemberDiv"> {# {{ project_members_form }}#} </div> <button type="submit" class="btn btn-primary my-5">Submit</button> </form> {% endblock %} I would like to add project_member_form based on some action (it does not really matter now what action). This is not working because it seems that JS is not able to see Python variable in <script> block. Here is issue I've got: EDIT: I have got single form without any functions working without any issues. Here is my render method: def project_generation(request): if request.method == 'POST': pass else: project_form = ProjectForm(prefix='Project') project_role_form = ProjectRoleForm(prefix='ProjectRole') project_members_form = ProjectMemberForm(prefix='ProjectMember') # logging.debug(project_form) # logging.debug(project_members_form) return render(request, "project_xml_generation.html", { "project_form": project_form, "project_members_form": project_members_form }, ) -
Django translation html not translating the string when html files are included using include statement
views.py: def process_request(request, data) context = { 'category': datacategory, 'info': data.abc 'language_code': language_code } return TemplateResponse(request, template='.../components/test.html', context=context) test.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hello world' %}</p> {% include 'hash_processor/components/test2.html' %} </div> test2.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hi... world234567' %}</p> {% include 'hash_processor/components/test3.html' %} </div> test3.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'heyy world234567' %}</p> </div> django.po: #: templates/hash_processor/components/test.html:6 msgid "hello world" msgstr "hgfghjkl wojehfvejh" #: templates/hash_processor/components/test2.html:6 msgid "hi... world234567" msgstr "hi....fjkherjfger kfhgerhjkf233" #: templates/hash_processor/components/test3.html:6 #, fuzzy #| msgid "hi... world234567" msgid "heyy world234567" msgstr "heyyy...ghewjfgdjhdfr kfhgerhjkf233" output on broswer: string coming for translation in django.po but not rendering in browser till level 2 it is working fine, but at 3 level translated string not showing -
Python Django Form - issue with checkboxes in ModelMultipleChoiceField
I have this model class ProjectMember(models.Model): member_name = models.CharField(max_length=100) member_uid = models.CharField(max_length=15) member_reviewer_uid = models.CharField(max_length=15) member_roles = models.ManyToManyField('ProjectRole', blank=False) member_discipline = models.ManyToManyField('ProjectDiscipline', blank=False) class ProjectRole(models.Model): role_name = models.CharField(max_length=10, unique=True) def __str__(self): return self.role_name this Form class ProjectMemberForm(forms.ModelForm): class Meta: model = ProjectMember fields = ( 'member_name', 'member_uid', 'member_reviewer_uid', 'member_roles' ) # member_roles = forms.ModelChoiceField( member_roles = forms.ModelMultipleChoiceField( queryset=ProjectRole.objects.all(), widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-control'}), required=True, # empty_label=None, # Hide the empty label for the select multiple widget. ) widgets = { 'member_name': forms.TextInput(attrs={'class': 'form-control'}), 'member_uid': forms.TextInput(attrs={'class': 'form-control'}), 'member_reviewer_uid': forms.TextInput(attrs={'class': 'form-control'}), } I have tried also the commented lines of code. I am still getting only this I would call it listbox instead of checkboxes: My issue is that I would like to have it as checkbox instead of this list to crosscheck everything I want to be active. EDIT: Note that I do not intent to save any data into database. This is going to act as configuration server and output is .xml file. -
How do I add custom field in swagger ui in django application?
With every request the api endpoint requires a header name 'VENDOR'. I need to create a field in Django swagger ui to add the VENDOR value and attach it to the headers in every request. I tried customizing swagger settings in Django settings but it didnot work I want something similar like the one in the image but has to be vendor in the field and add to its the request image link -
Unable to display dash-plotly graph in webapp written with django/angular
The company were I work is building a website that is supposed to show some graphs and statistics. The front-end is written in angular and the back-end in python. I would like to use dash to create the plots but I'm having a hard time displaying my test dash app. In the front end there is a button 'draw graph' that when pressed should open a new window with where the app is shown. I tried following the django-plotly-dash tutorial but for some reason I cannot make it work. I'm relatively new to django btw. I have a graph app in the django project. My testing dash app is in dash_app.py and it contains a button that does nothing. from dash import html from django_plotly_dash import DjangoDash app = DjangoDash("Test") app.layout = html.Div([html.Button("Submit", id="submit-value")]) My template is dash_template.html <!DOCTYPE html> <html> <head> <title>Dashboard</title> {%load plotly_dash%} </head> <body> <h1>Dashboard Test</h1> {%plotly_app name="Test" %} </body> </html> And the views.py looks like this. def dash_view(request): return render(request, "graph/dash_template.html") When I click the the draw_graph button, the new window opens and the header Dashboard Test is displayed but the Submit button does not appear. I have already added path("django_plotly_dash/", include("django_plotly_dash.urls")) to the project urls.py … -
Django Email Sending Issue: Email Not Sent and Not Appearing in Sent Items
I'm working on a Django project where I need to send an email with an attached PDF file. My current setup is as follows: Django Version: 4.0.3 Python Version: 3.12.2 Problem: The code runs without throwing any errors. However, the email is not being received by the recipient. The email is also not appearing in the "Sent" folder of the sending Gmail account. Things I've Tried: Verified that the email configuration in settings.py is correct, using the Gmail SMTP server. Checked that the PDF file exists at the specified path. Ensured that there are no exceptions thrown during the email sending process. Tried sending a simple email without attachment, but still no success. Checked Gmail account security settings, including enabling "Less secure app access" and using an App Password. ** Questions: ** What might be causing the email to not be sent or appear in the sent items? Are there any additional debugging steps I can take to figure out what's going wrong? Could there be an issue with Gmail's SMTP server, or is there something I might be missing in the Django configuration? def send_email(request, customer_id): try: order = customer_agent.objects.get(customer_id=customer_id) except customer_agent.DoesNotExist: return HttpResponseNotFound("Order not found") subject = 'Your … -
CSRF issue while calling the api from the frontend [closed]
Create_admin.py def create_agent(request): if request.method == 'POST': name = request.POST.get('name') username = request.POST.get('username') password = request.POST.get('password') if name and username and password: agent = Agent.objects.create(name=name, username=username, password=password) return JsonResponse({'status': 'success'}) return JsonResponse({'status': 'failed'}, status=400) return render(request, 'superadmin/create_agent.html') @user_passes_test(is_super_admin) def fetch_payments(request): if request.method == 'GET': payments = Payment.objects.all().values() # Fetch all payment data return JsonResponse(list(payments), safe=False) class PaymentListView(APIView): def get(self, request): payments = Payment.objects.all() data = [ { "id": payment.id, "agent_name": payment.agent_name, "amount": payment.amount, "payment_link": payment.payment_link, "status": payment.status, "created_at": payment.created_at, } for payment in payments ] return JsonResponse(data, safe=False) create_admin.jsx const handleCreateAgent = async (e) => { e.preventDefault(); const csrfToken = getCSRFToken(); // Get the CSRF token try { const response = await axios.post('http://127.0.0.1:8000/api/superadmin/create-agent/', { username, password, name: agentName, }, { headers: { 'X-CSRFToken': csrfToken, // Include the CSRF token in the headers }, withCredentials: true }); setMessage('Agent created successfully!'); setUsername(''); setPassword(''); setAgentName(''); } catch (error) { console.error('There was an error creating the agent!', error); setMessage('Failed to create agent.'); } }; Forbidden (CSRF cookie not set.): /api/superadmin/create-agent/ [13/Aug/2024 12:32:07] "POST /api/superadmin/create-agent/ HTTP/1.1" 403 2869 This the error that i'm getting when calling the api from the frontend.isssue is that i have already set the cookies thing CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = … -
Can't use psycopg3 on Mac?
My Django project currently uses psycopg2. When I try to switch to psycopg3, I get the following error: OSError: cannot load library 'pango-1.0-0' I tried upgrading pip, reinstalling pango, and I also tried starting over with a fresh virtualenv. I still get the same error. I'm using Django 4.2 with Python 3.10 -
Django,There is no module named "myapp"
enter image description here PS C:\Users\taipe\firstproject> & C:/Users/taipe/AppData/Local/Programs/Python/Python312/python.exe c:/Users/taipe/firstproject/firstproject/urls.py Traceback (most recent call last): File "c:\Users\taipe\firstproject\firstproject\urls.py", line 19, in from myapp.views import sayhello,sayhello2,hello3 ModuleNotFoundError: No module named 'myapp' PS C:\Users\taipe\firstproject> enter image description here I don`t know why there is the problem of "no module named "myapp" ". however, there actually is a "myapp" folder in my "firstproject". -
Django generic DetailView: what is the best way to optionally include a reverse-related object?
Background Models Let's say I have a django generic DetailView that I use to display a single object instance of a model called Car. Then let's say I have another model called Race. Among many fields, this Race model has a ForeignKey field that is linked to Car (i.e., the Car that a Driver (user) used for a Race). Example models.py from django.conf import settings class Car(models.Model): """ a bunch of fields, including many fk fields """ class Race(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="races") driver = models.models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) """ a bunch of other fields, including fk fields """ View Now let's say I have a generic DetailView that my website's users have used for a long time to see a single car object. Example views.py This has a very simplified queryset (my actual queryset has the same sort of structure but more reverse-related fields with their respective related fields). from django.views import generic class CarDetailView(generic.DetailView): model = Car queryset = Car.objects.select_related( """ a bunch of related fields """ ).prefetch_related( """ some reverse related fields """, Prefetch(""" a reverse related field """, SomeReverseRelatedField.objects.select_related(""" some of its related fields """)), ) New feature :) Recently, however, I've implemented a way for my … -
Django: how do I make a dependent dropdown load a filtered list of objects on the update form?
I have multiple dependent dropdowns throughout my application. To add a new record, the form works as expected; for example, you select a Country and the list of State objects for that Country will load, you then select a State and the Suburb objects for that State will load. You save the record, it has all the fields saved correctly, you view the record and all the info can be viewed all as expected. The problem I have is when I want to change/update the record. The instantiated SuburbForm is told to first load a blank dropdown for State, and call a function load_dropdowns when the parent object Country has been set. This action of calling load_dropdowns does not seem to happen in the update form, instead it just stays blank, even if I try to re-select the parent. If I change the instantiated form to load all objects instead of the blank dropdown, the update form fills in the field correctly, but that means the add new and update forms now load all objects instead of the filtered list. models.py from django.db import models class Country(models.Model): item_name = models.CharField(verbose_name="Country") class State(models.Model): item_name = models.CharField(verbose_name="State") state_in_country = models.ForeignKey(Country, on_delete=models.SET_NULL, verbose_name="Country", … -
How to concatenate in Dango annotate()
I want to concatenate a string variable with one of my field, but can't figure out what I'm doing wrong I tried this, where prefix is a string and filename_mask is a field in the table plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask') ) .values('name', 'description', 'filename') ) I get the error Expression contains mixed types: CharField, TextField. You must set output_field. even though I'm concatenating 2 String type. So I added output_field plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask', output_field=CharField()) ) .values('name', 'description', 'filename') ) but this gives me the error "'CharField' object has no attribute 'get_internal_type'" -
Nested Serializer with Foreign Key and to_field
Stock model has a OneToMany relationship with Data model. I am using the to_field to link them via model_number field. class Stock(models.Model): model_number = models.CharField(max_length=100, unique=True, null=True) model = models.CharField(max_length=100) brand = models.CharField(max_length=100) msrp = models.IntegerField(default=0) def __str__(self): return f"{self.brand} - {self.model} - {self.model_number}" class Data(models.Model): model_number = models.ForeignKey(Stock, to_field='model_number', on_delete=models.CASCADE) price = models.FloatField() date = models.DateField() def __str__(self): return self.model_number I have my serializers to show each model number and then the nested relationship of data. class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class StockSerializer(serializers.ModelSerializer): data = DataSerializer(many=True, read_only=True) class Meta: model = Stock fields = ['brand', 'model', 'model_number', 'msrp', 'data'] However the price does not return at all in my API view. Not sure where I am going wrong on this. -
Django 5 update_or_create reverse one to one field
On Django 4.x Code is working as expected from django.db import models class Project(models.Model): rough_data = models.OneToOneField( "Data", related_name="rough_project", on_delete=models.SET_NULL, null=True, blank=True, ) final_data = models.OneToOneField( "Data", related_name="final_project", on_delete=models.SET_NULL, null=True, blank=True, ) data, created = Data.objects.update_or_create( rough_project=project, defaults=data ) On Django 5.x: ValueError: The following fields do not exist in this model: rough_project I do not see any changes related to this in changelog -
Django- How to retrive ChoiceField value from a form?
I want to get the selected choice from a ChoiceField in a view. When I submit the form, I process it in a view: views.py def myFormSubmitView(request): ... if form.is_valid(): print("valid form") post = Post() post.title = form.cleaned_data["title"] post.body = form.cleaned_data["body"] **>>>>post.choice_test = form.cleaned_data["choice_test"]** post.save() return HttpResponseRedirect(request.path_info) I want to get the value of choice_test. How can I do that ?