Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering in my project not working (django restframework)
I'm building APIs with django and I have been trying to implement filtering into the system but the filter option just brings back all the list. Below is my codes view.py from unicodedata import name from django.shortcuts import render, get_object_or_404 from rest_framework import generics, status from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from .serializers import DailySalesSerializer, DailySalesCreateSerializer from .models import DailySales # Create your views here. class DailySalesListView(generics.GenericAPIView): serializer_class = DailySalesSerializer queryset = DailySales.objects.all() name = 'Daily Sales List' filter_backends = (DjangoFilterBackend,) filterset_fields = ('id', 'customername','havepaid', 'datesold', 'itemsold') def get(self, request): sales = DailySales.objects.all() serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) I have also added django_filters to my settings.py -
Django Template Variable not found
I'm pretty new to Django and I'm really struggling with this issue. So if anyone can help I would be very grateful :). Basically everytime I access the path to reach one specific profile, the variable {{profile.user.username|default="Not found"}} does not get recognised and the default value is the output. When I access another path like profile_list, the right output comes up from the same variable. Both html pages(profile.html and profile_list.html) inherit from base.html. Any idea where the issue might be or where I should be looking into? -
How to preserve values from multiple select objects on one form using Django HTMX
Picture a todo list with multiple columns that include Priority, Status, AssignedTo, Due Date. Now I have a form below this list that has a ChoiceBox (and in one case ModelChoiceBox) for each of these conditions. So set Priority to 2, and the list refreshes to just 2's. Now select Status = 3 for example, and the two filters should be combined. In my View however, they are not. The value of the most recent Select comes over, but he previous value is reset to None. Here is a slimmed down example with just 2 Selects. class FilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.attrs = {"novalidate": '', } priority = forms.ChoiceField( choices=PRIORITY_CHOICES, widget=forms.Select(attrs={ 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-trigger': 'change' }) ) status = forms.ModelChoiceField(queryset=TaskStatus.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('change-priority'), 'hx-target': '#tasklist', 'hx-trigger': 'change' }) ) Here is a scaled down View: def change_priority(request): filtform = FilterForm(request.POST) form = NotePadForm(request.GET) fpriority = form["priority"].value() fstatus = form["status"].value() tasklist = get_object_or_404(TaskList, owner=request.user) if tasklist: tasks = Task.objects.filter(priority=fpriority, status=fstatus) filtform = FilterForm() context = { "tasks": tasks, "filtform": filtform, "form": form } return render(request, "planner/partials/tasklist.html", context) return HttpResponse("Error - No Valid Task List") So changing Priority sends the correct Selected value to … -
Django Project on Port 80 while running on localhost?
I want to run a local django project on port 80 instead of default 8000 while running the project on localhost. -
How to add the name of an uploaded file to a model in django
I am learning django. I am stuck with this problem. I have created a form in which a user uploads a text file and selects a gender. The user is also supposed to write the name of the text file in the text box. sample output In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output. As I have already mentioned the user needs to type the name of the file, I was thinking is it possible to get the name of the file from the uploaded file and then save it to the model so the user need not type the name of the file and hence no text box. Here is the link to my git repository - https://github.com/AnshulGupta22/auto_generation.git Can someone please tell me how to do it? As I already said I am new to django and some help will be appreciated. -
Erreur: HTTPConnectionPool(host='dnode2', port=9864): Max retries exceeded with url: /webhdfs
I'm trying to read a file on my hdfs server in my python app deployed with docker, during dev, I don't have any problem, but in prod there are this error : Erreur: HTTPConnectionPool(host='dnode2', port=9864): Max retries exceeded with url: /webhdfs/v1/?op=OPEN&namenoderpcaddress=namenode:9000&offset=0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1af13d45d0>: Failed to establish a new connection: [Errno -2] Name or service not known')) Note that I use an address IP not that "dnode2" name and neither use that port!! please any body can help -
Integrity Error - Foreign Key constraint failed when uploading image to data bank Django Imagefield
This is part of my class in models.py class Account(AbstractBaseUser): email=models.EmailField(verbose_name="Email", max_length=60, unique=True) nick_name=models.CharField(verbose_name="Nickname", max_length=20) null=True, profile_img=models.ImageField(upload_to=upload_location,null=True, blank=True, default=None) #necessary date_joined=models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login=models.DateTimeField(verbose_name="last login", auto_now_add=True) is_admin=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) is_superviser=models.BooleanField(default=False) this is my receiver in models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def post_save_compress_img(sender, instance, *args, **kwargs): if instance.profile_img: picture=Image.open(instance.profile_img.path) picture.save(instance.profile_img.path, optimize=True, quality=30) settings.py: AUTH_USER_MODEL = 'account.Account' whats wrong in here that I run into an integrity error? -
i get this error OperationalError at /admin/accounts/student/
hey guys i work withe django framework i had the error OperationalError i have to class with same fields class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) First_Name = models.CharField('First Name', max_length=30, null=True, blank=True) Last_Name = models.CharField('Last Name', max_length=30, null=True, blank=True) ID_Number = models.CharField('Id Number', max_length=30, null=True, blank=True) Phone = PhoneNumberField('Phone',null=True) class Meta: verbose_name_plural = "Students" def __str__(self): return str(self.user) class Lecturer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) First_Name = models.CharField('First Name', max_length=30, null=True, blank=True) Last_Name = models.CharField('Last Name', max_length=30, null=True, blank=True) ID_Number = models.CharField('Id Number', max_length=30, null=True, blank=True) Phone = PhoneNumberField('Phone',null=True) class Meta: verbose_name_plural = "Lecturers" def __str__(self): return str(self.user) and i add new field to my Student and also to Lecturer classes the field is Phone = PhoneNumberField('Phone',null=True) and yes i did the commands: python manage.py makemigrations python manage.py migrate after that i get prove that every thing is update: Operations to perform: Apply all migrations: HomePage, accounts, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. but when i run the runserver and after the i go to the url http://localhost:8000/admin add i go the Lecturers data every things work great i have new field Phone but when i try … -
Django + EC2 + Apache giving SERVER ERROR 500
I've worked on a Django project locally and everything was working fine. I deployed it on EC2 Ubuntu instance alongwith Apache2 and it is giving a server error 500. I've tried with gunicorn+nginx as well, still no joy. So as a context, I'm using Django4, Python3, Apache2 alongwith; AWS RDS for postgres DB AWS S3 for static files (Both are working fine in dev and prod mode locally). I've also added my EC2 IP address to ALLOWED_HOSTS and still the same (also getting same error if I allowed everything by *). Note: I've all my credentials in .env file. Somehow the Django application isn't providing access. I actually want to get an SSL from CertBot and assign my purchased .dev domain. I'm actually stuck here for past couple of days, gone though several blogs but not able to get this resolved. Any suggestions would be of massive help. Thanks. my apache .conf file <VirtualHost *:80> ServerAdmin admin@admin.com ServerName <aws_public_ip_address> ServerAlias <aws_public_ip_address> DocumentRoot /home/ubuntu/liveProject/Django-Project ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/liveProject/Django-Project/static <Directory /home/ubuntu/liveProject/Django-Project/static> Require all granted </Directory> Alias /template /home/ubuntu/liveProject/Django-Project/tempate <Directory /home/ubuntu/liveProject/Django-Project/tempate> Require all granted </Directory> <Directory /home/ubuntu/liveProject/Django-Project/ProjectName> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Django-Project python-path=/home/ubuntu/liveProject/Django-Project python-home=/home/ubuntu/liveProject/liveEnv WSGIProcessGroup … -
Hi when i create contact us form in Django this integrity error shows
Here is the error screenshot My code is def contacts(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') contact = Contact(name=name, email=email, phone=phone, desc=desc, date=datetime.today()) contact.save() return render(request, 'contacts.html') and my model code is from django.db import models Create your models here. class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phone = models.CharField(max_length=12) desc = models.TextField() date = models.DateField(auto_now_add=True) -
Understanding pytest-django test arguments
What are 'rf' and 'user_context' parameters and when are they assigned? import pytest from rest_framework import status from rest_framework.reverse import reverse from request_helper import pytest_request @pytest.mark.urls(urls='api.urls') @pytest.mark.django_db def test_user_name_check_200(rf, users_context): data = { 'username': 'test_jay_2' } url = reverse(viewname="users-check") response = pytest_request(rf, method='get', url=url, user=None, data=data) assert response.status_code == status.HTTP_200_OK Thanks in advance. -
heroku app push rejected, failed to compile python app, push failed
I'm trying to make a django website and ran into this problem,please tell me how to fix it, if you need more info please tell me,I also should mention, the old versions are loading but now I cant push any new versions to the site build log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.8.13 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.8.12 -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 414, in execute self.check(tags=self.requires_system_checks) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 488, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. ! Error while running … -
Should I authenticate DRF in that case in some way?
I made a react+django web app that is actually just a simple react form that sends data to django-rest-framework api view which saves form in database and sends an emails it to me. React app does not utilize any user system, anyone can send their form. Should I authenticate requests to DRF in some way? Also- when user types www.example.com/api/modelapi he can access the data- should i prevent this behaviour somehow? -
How to update User password in django
I'm having trouble when i try to update user password in django. def password(request): if request.method=="POST": password =request.user.password username=request.user.username c_password=request.POST["current_password"] new_password=request.POST["new_password"] r_new_password=request.POST["retype_new_password"] if password==c_password: if new_password==r_new_password: user =User.objects.get(username=username) user.set_password(new_password) user.save() messages.info(request,"Successfully saved") else: messages.info(request,"PASSWORD DOES NOT MATCH") else: messages.info(request,"PASSWORD INCORRECT") return render(request,"security.html") When i fill the current password, it is giving me error password incorrect. But, when i fill pbkdf2_sha256$320000$Cb4s4nwqKwirdgo50ZdjLH$aeuSP3X+dSZXsv0XJB0XxkpwfsmU+PedMX9Jl50Zark= , my password becomes correct and user password is updateable. My problem is I would like to fill in current password field as normal current password without getting the error. -
Display post to only user friends
When user login i want user to only see the post of friends with, I have a separate model for friends and a separate for post how do i filter post by users friends ? Here is my view def post_list(request): for user in Post.objects.all(): if request.user.is_authenticated: friend_list = FriendList.objects.get(user=request.user ) friends = friend_list.friends.all() context['friends'] = friends context['posts'] = Post.objects.prefetch_related('comments').filter(username=friends).order_by('-date_posted') return render(request,'feed/feed.html',context) Post model class Post(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True) date_posted = models.DateTimeField(auto_now_add=True) video = models.FileField(upload_to="videos",blank=True,null=True) tags = models.CharField(max_length=100, blank=True) views = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="view") shared_body = models.TextField(blank=True, null=True) shared_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='+') shared_on = models.DateTimeField(blank=True, null=True) -
How can I refactor this model in Django?
I want to refactor this model(code) from Django so that I can take as many inputs as required without writing a lot of code or efficiently. Or Can I use for loop in models? models.py class Sales(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE) prescribed_doctor = models.CharField(blank=True,max_length=150) date_created = models.DateTimeField(default=timezone.now) sales_medicine_1 = models.ForeignKey(Medicines,related_name='sales_medicine',on_delete=models.CASCADE) Med_quantity_1 = models.IntegerField(blank=False,default=1) Free_quantity_1 = models.IntegerField(blank=True,default=0,null=True) margin_1 = models.PositiveIntegerField(blank=True,default=0,null=True) discount_1 = models.FloatField(choices=dis,default=0,null=True) discount_1_amt = models.FloatField(default=0,null=True) rate_1 = models.FloatField(blank=True,default=0,null=True) batch_no_1 = models.CharField(null=True,blank=True,max_length=50) mfg_1 = models.CharField(max_length=50,blank=True,null=True) expiry_1 = models.CharField(max_length=20,null=True,blank=True) sales_medicine_2 = models.ForeignKey(Medicines,blank=True,null=True,related_name='sales_medicine_1',on_delete=models.CASCADE) Med_quantity_2 = models.IntegerField(blank=True,default=0,null=True) Free_quantity_2 = models.IntegerField(blank=True,default=0,null=True) margin_2 = models.PositiveIntegerField(blank=True,default=0,null=True) discount_2 = models.FloatField(choices=dis,default=0,null=True) discount_2_amt = models.FloatField(default=0,null=True) rate_2 = models.FloatField(blank=True,default=0,null=True) batch_no_2 = models.CharField(null=True,blank=True,max_length=50) mfg_2 = models.CharField(max_length=50,blank=True,null=True) expiry_2 = models.CharField(max_length=20,null=True,blank=True) sales_medicine_3 = models.ForeignKey(Medicines,blank=True,null=True,related_name='sales_medicine_2',on_delete=models.CASCADE) Med_quantity_3 = models.IntegerField(blank=True,default=0,null=True) Free_quantity_3 = models.IntegerField(blank=True,default=0,null=True) margin_3 = models.PositiveIntegerField(blank=True,default=0,null=True) discount_3 = models.FloatField(choices=dis,default=0,null=True) discount_3_amt = models.FloatField(default=0,null=True) rate_3 = models.FloatField(blank=True,default=0,null=True) batch_no_3 = models.CharField(null=True,blank=True,max_length=50) mfg_3 = models.CharField(max_length=50,blank=True,null=True) expiry_3 = models.CharField(max_length=20,null=True,blank=True) Payment_status = models.CharField(max_length=15,choices=payment_status) Paid_amount = models.FloatField(blank=True,default=0,null=True) auto_generated = models.BooleanField(default=False) -
I want max duration_seconds of distinct character in elasticsearch
here is the query which I have write it was working fine in my kibana console but when I am trying this in Elasticsearch Head(chrome extension for Elasticsearch queries) and DSL library (Django library for elastic) it's not working. RAW query - { "query": { "range": { "create_datetime": { "gte": "2022-01-21T14:32:12+00:00", "lte": "2022-03-21T14:32:12+00:00" } } }, "size": 0, "aggs": { "unique_character_objid": { "terms": { "field": "character_objid", "size": 100 }, "aggs": { "theMax": { "top_hits": { "size": "1", "sort": { "approved_duration_seconds": { "order": "desc" } } } } } } } } DSL query : video_sessions_elastic = VideoSessionDocument.search().query('range', create_datetime={'gte': from_last_thursday, 'lte': to_wednesday}) aggs_var = A('terms', field='character_objid.keyword') video_sessions_elastic.aggs.bucket('distinct_character_objid', aggs_var) -
Django python mysql shell error while opening the shell
while connecting the Django with MySQL and opening the shell using python3 mannage.py shell I got this error -
how can I tab scroll items in image gallery in django with javascript
Please i am trying to do a tab image gallery in django using javascript to activate it dynamically. I have tried all i know but i dont know how to pass the variable to onclick="currentSlide()" to make it work incrementally . Please i am trying to do a tab image gallery in django using javascript to activate it dynamically. I have tried all i know but i dont know how to pass the variable to onclick="currentSlide()" to make it work incrementally . Please i am trying to do a tab image gallery in django using javascript to activate it dynamically. I have tried all i know but i dont know how to pass the variable to onclick="currentSlide()" to make it work incrementally . #template -property_info.html <div class="container"> <!-- Full-width images with number text --> {% for p in images %} <div class="mySlides"> <div class="numbertext">1 / 6</div> <img src="{{p.images_of_property.url}}" style="width:100%"> <h1>{{p.id}}</h1> </div> {% endfor %} <!-- Next and previous buttons --> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <!-- Image text --> <div class="caption-container"> <p id="caption"></p> </div> <!-- Thumbnail images --> this is where i have issues . i dont know how to pass the value so it can increment dynamically. {% … -
Django views.py if statement not passing value to HTML File
In my Django views.py page, I have some code, where the user enter an employee ID with an HTML form, that submits the value to views.py. Using that, I check whether the employee ID is in a database by iterating over each ID in the database, appending it to an empty list, and using an if statement. The parts where I receive the employee ID is working fine, and so is the ID getting appended to the list. However, when I use an if statement to check whether the employee ID that was given is a part of the list, isn't working. Despite this working on Jupyter Notebook when i tested the same. Here's the code: views.py: from django.shortcuts import render import pandas as pd dat = pd.read_csv('/Users/Lenovo/Desktop/Cakewala DB/CW_Attendance/AttendanceApp/test_employee.csv') # Create your views here. def home(request): employee_id = request.POST.get('id') print(employee_id) id_list = [] for id in dat["ID"]: id_list.append(id) print(id_list) if employee_id in id_list: print("yes") employee_row = dat.loc[dat["ID"] == employee_id] employee_name = employee_row.iat[0, 1] return render(request, 'attendance/index.html', { "employee_id": employee_id, "employee_name": employee_name }) return render(request, 'attendance/index.html') index.html: <!DOCTYPE html> <html> <head> <title>Attendance - Home</title> </head> <body> <h1>Cakewala Attendance</h1> <form method="POST"> {% csrf_token %} <label for="id">Employee ID</label> <br> <input type="number" name="id" max="9999" … -
How to solve the problem that json type data is loaded from template to string type
The "content" field is data in json format. But when I check this value in template , it resolves to string. I want to print the value corresponding to teacher from the dictionary below. What's wrong? [views.py] history = History(user=request.user, study=study, content=study.json()) history.save() test = History.objects.filter(study__id='12') "content" value stored in DB: {'id': 12, 'is_deleted': False, 'type': 'secondary', 'study_name': 'Math', 'teacher': 'Halen/Lisa', 'team': 'A'} [html] {% for test in test %} {{ test.content.teacher }}? {{ test.content}} {% endfor %} In the case of a dictionary, the desired key value can be called, but since it is a string type, the teacher value cannot be retrieved. What should the teacher do to get the value, which is the key? -
How can I host a Django web app on Cpanel out the public_html folder?
I am trying to host a Django web application on Cpanel. However, my hosting service is having a main folder which is called public_html. In this folder, there is the index page. My project folder named myapp is out of the public_html folder. Whenever I run the application, it is showing the content of the index.html which is in the public_html folder instead of running the home page of my application that should be executed from this main urls.py file. Bellow is the main urls.py content. from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('depenses/', include('depenses.urls', namespace='depenses')), path('cart/', include('cart.urls', namespace='cart')), path('orders/', include('orders.urls', namespace='orders')), path('coupons/', include('coupons.urls', namespace='coupons')), path('', include('shop.urls', namespace='shop')), # path('', TemplateView.as_view(template_name='templates/index.html'), name='home'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Again my project is out of the public_html folder. Please assist me to host my application. -
How to I allow user to upload any type of file in database in Django?
I want to accept any type of file from the user and save it in the database in Django <input type="file" name="file_name" required> But when I try to access the file in views.py it throws the Exception as 'file_name'. file_name = request.FILES['file_name'] In the same field when I select some image. The image is stored in the media folder. -
Django: Defining 'present_company' from 'company_name' ManytoManyField
I have 2 models, Company and Employee, and defined company history as a ManytoManyField. I am trying to save the present company name of the employee which I get from the company name ManytoManyField. What should be the method to save it? This is what I tried: I tried to override the save method in Models. models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class Employee(models.Model): name = models.CharField(max_length=100) company_name = models.ManyToManyField(Company, blank=True) present_company = models.CharField(max_length=100, blank=True) def save(self): super(Employee, self).save() last_index = self.company_name.count()-1 self.present_company=str(Company.objects.filter(employee__name=self.name)[last_index]) super(Employee, self).save() def __str__(self) -> str: return self.name I face two problems with this method: I add/edit the models from the admin site, when I try to save the models and print the names of the company, it prints out the previous edit and not the latest one. The order of the companies is not according to the order in which I save the models. So, what could be the changes in this method, or, some other method to do this job. -
Django Prefetch Related Issue - Understand it correctly
I do have the following Issue - I want to display all of the bundles with their component relations in a template: Here is my ORM-Model: class Component(models.Model): plenty_var_number = models.CharField(max_length=120, default=None, unique=True, null=True) plenty_var_id = models.CharField(max_length=120, default=None, unique=True) description = models.TextField(max_length=1000) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return f"{self.category.name} - {self.plenty_var_number}" class Bundle(models.Model): active = models.BooleanField(default=True) plenty_var_number = models.CharField(max_length=120, default=None, unique=True, null=True) plenty_var_id = models.CharField(max_length=120, null=True, default=None) car = models.ForeignKey(Car, on_delete=models.DO_NOTHING) # m2m defined by BundleComponentRelation components = models.ManyToManyField(Component, through="BundleComponentRelation") linked_to_plenty = models.BooleanField(default=False) price = models.DecimalField(max_digits=10, decimal_places=2, default=-1.00) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class BundleComponentRelation(models.Model): component = models.ForeignKey(Component, on_delete=models.DO_NOTHING) bundle = models.ForeignKey(Bundle, on_delete=models.DO_NOTHING) qty = models.IntegerField(default=1) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) I have played around with select_related and prefetch_related in my view to pass them via context to the template to display it for my users: html-template: {% for bundle in bundles %} <tr> <td><p class="fw-bold">{{ bundle.plenty_var_number }}</p></td> <td>{{ bundle.price }}</td> <td><p class="fw-bolder mb-0">{{ bundle.car }}</p> <p class="mb-0">{{ bundle.car.roof_type }}</p> <p class="mb-0">BJ: {{ bundle.car.production_start }} - {{ bundle.car.production_end }}</p> </td> {# Bundle Component Relations here #} <td style="font-size: …