Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating object in bulk and then serialize them
model: class ProductImage(models.Model): post = models.ForeignKey(Product,...) image = models.ImageField(...) view: pobj = Product.objects.get(user=request.user, id=id) nimg = int(request.data['numofimg']) for i in range(nimg): image = request.data[f'image{i}'] obj = ProductImage.objects.create(post=pobj, image=image) pobjs = Product.objects.all() serialerize = ProductImageSeriailzer(pobjs, many=True) # it would be better if pobjs only have newly created objects (in above for loop) Is their any efficient code for the same? Here number of queries will increase with number of image How can i reduce them? -
How to avoid list index out of range in Django ORM query
I have a tricky scenario here ,usually I get 6 values from the below query , basically prices at start and month end of the month, prices value will be there every time trade_date price 01-01-2021 120.2 31-01-2021 220.2 01-02-2021 516.2 28-02-2021 751.0 01-03-2021 450.2 31-03-2021 854.9 and I need Sum of 1st month starting price + 1st month Ending price + every months ending price ie 120.2+220.2+751.0+854.9 but in some cases, last month data tend to miss, how to handle those scenarios monthly_values = Items.objects.filter(trade_date__gte=quarter_start_date, trade_date__lte=quarter_end_date).values_list('price', flat=True).order_by('trade_date') total_sum = monthly_values[0]+monthly_values[1]+monthly_values[3]+monthly_values[5]) Currently getting list index out of range from the above because of missing values -
Get count of second-degree foreign-key entities in Django
We have a data model with three basic models: Group Activity Participant Groups are related (FK) to activities. Activities are related (ManyToMany) to participants. I want to take all activities related to the group and then count all participants of that set of activities. How can I count all activity participants for all group activities from a given group? -
How to properly open a bootstrap modal that is on another file on django
I have a django app with two template file: a page.html and a modal.html and I am trying to implement a system where if a user clicks on a btn on the page.html, the modal.html is rendered as a modal. I tried to do it using django-bootstrap-modal-forms but I couldn't really get what I need because the library seems to be built around creating modals and forms in a very specific way. Specifically, the problem I am facing with this implementation is that if a user "close" the modal they are sent to another url and not to the page.html url. So basically the modal isn't dismissed properly. This is what I did so far but I am really open to different approaches using Bootstrap only. page.html ... <a id='UploadFile' class="list-files__btn-plus" href="#"> <img src="{% static 'action/img/project/files/icon_plus-file.svg' %}" alt="+"> </a> ... <script src="{% static 'action/js/project/files/files.js' %}"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#UploadFile").modalForm({ formURL: "{% url 'action:ModalFileUpload' %}", }); </script> modal.html ... urls.py path('modal/fileupload', file_upload.ModalFileUpload.as_view(), name='ModalFileUpload'), views.py class ModalFileUpload(MyLoginRequiredMixin,TemplateView): template_name = 'modal.html' -
How to get id from function in Django
hollo dears, I'm working on a project I have a problem with my code below, I can't get the subject_id from URL and save it in the Grade model, it gets None value.error is: Subject matching query does not exist. Grade model: class Grade(models.Model): id=models.AutoField(primary_key=True) student= models.ForeignKey('Student', null=True,on_delete=models.PROTECT) classwork= models.ForeignKey('ClassWork',on_delete=models.PROTECT) section= models.ForeignKey('Section', null=True,on_delete=models.PROTECT) subject= models.ForeignKey('Subject',null=True, on_delete=models.PROTECT) grade = models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) description = models.TextField(max_length=500, null=True) assignment1=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) assignment2=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) assignment3=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) Views.py def newgrade(request, subject_id): # subject=Subject.objects.get(id=subject_id) classwork = ClassWork.objects.filter(teacher_id=request.user.id) student=Student.objects.filter(classwork__subject__id=subject_id) context = { "classwork": classwork, "student":student, "subject":subject, } return render(request, 'myapp/teacher_template/newgrade.html', context) def newgrade_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('newgrade') else: subject_id = request.POST.get('subject') assignment1 = request.POST.get('assignment1') assignment2 = request.POST.get('assignment2') assignment3 = request.POST.get('assignment3') final = request.POST.get('final') sutudent_id= request.POST['student_select'] #the error is here, i want to get subject_id value from URL, and save it Grade model subject_obj = Subject.objects.get(id=subject_id) # try: # Check if Students Result Already Exists or not check_exist = Grade.objects.filter(subject_id=subject_obj, student_id=student_obj).exists() if check_exist: grades = Grade.objects.get(subject_id=subject_obj, student_id=student_obj) grades.assignment1 = assignment1 grades.assignment2 = assignment2 grades.assignment3 = assignment3 grades.final = final grades.grade= assignment1 + assignment2 + assignment3 + final grades.save() messages.success(request, "Result Updated Successfully!") return redirect('newgrade') else: result = … -
How to solve ERR_TOO_MANY_REDIRECT when deploying django rest framework web app to Azure?
I deployed an web app which django restframework base on Heroku and Azure. Same app on Heroku works fine. But when I access to Azure, it causes ERR_TOO_MANY_REDIRECT error. I googled and found that turn SECURE_SSL_REDIRECT off solved ERR_TOO_MANY_REDIRECT error. However, it causes 403 CSRF error instead. I need to find another way to fix ERR_TOO_MANY_REDIRECT or find a way to fix 403 CSRF error. Can anyone help me to solve this issue? -
Django & Ajax: How to take multiple option value in select input and save to database
I have a form where I can select multiple tags to a a single project. I am using ManyToMany Field for the tag attribute. I am using AJAX for my POST request with form data. My problem is the form won't save with multiple selected options. Any solutions? --views.py def create_project_view(request): form = ProjectForm() if request.is_ajax and request.method == 'POST': form = ProjectForm(request.POST, request.FILES) proj_title = request.POST.get('title', False) if form.is_valid(): instance = form.save(commit=False) instance.owner = request.user form.save() return JsonResponse({'title': proj_title}, status=200) context = { 'form': form } return render(request, 'projects/project-form.html', context) --project-form.html with AJAX <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> {% if project %} <a class="backButton" href="{% url 'project' project.id %}"><i class="im im-angle-left"></i></a> {% else %} <a class="backButton" href="{% url 'projects' %}"><i class="im im-angle-left"></i></a> {% endif %} <br> <form class="form" method="POST" id="form" action="" enctype="multipart/form-data">{% csrf_token %} {% for field in form %} <!-- Input:Text --> <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" /> </form> </div> </div> </main> <script> $(document).ready(function(){ $('#form').on('submit', function(e){ e.preventDefault() var formData = new FormData(); formData.append('title', $('#id_title').val()) formData.append('description', $('#id_description').val()) formData.append('featured_image', $('#id_featured_image')[0].files[0]) formData.append('demo_link', $('#id_demo_link').val()) formData.append('source_link', $('#id_source_link').val()) formData.append('tags', $('#id_tags').val()) formData.append('csrfmiddlewaretoken', $('input[name=csrfmiddlewaretoken]').val()); console.log(formData) $.ajax({ url: '{% url "create-project" %}', type: 'POST', … -
django rest frame work api with images, not displaying with <img src=" "> in html
i have made an images api with django rest frame work. when it is running server on goorm ide, it is okay to display but on the oracle cloud vm it is not displaying images on my in html is there any difference between runningn server on goorm ide and oracle cloud vm? -
Algorithm for finding shortest connection between friends in social network or betweent two wiki articles
I have models in Django like from django.db import models class TypeOfObject(models.Model): type = models.CharField(max_length=150, unique=True) def __str__(self): return self.type class Object(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) type = models.ManyToManyField(TypeOfObject, related_name='type_of_object', blank=False) relation = models.ManyToManyField('self', related_name='relation', blank=True, null=True) def __str__(self): return self.title Object can be Person or Article or Movie etc. They refers to each other. How to check, for example, how connected film Spider Man and Michael Jackson. We can find artists who starred in films, for example, Stoney Jackson and he starred in film with actor who starred in Spider Man. Lets count it for 1. And etc, we can estimate how some object related to another. Which way it better to do? -
Access cleaned data from django admin for pdf processing
Hi there I'm fairly new to django so please be kind if anything sounds a bit newbie to you. I am currently trying to add a print button to every existing django admin view of a project so it will not depend on a single model I could resolve manually for printing but every existing model which contains foreign keys to other models an so on. For simplicity I thought it would be the best to just get the cleaned_data of the form and process it for the pdf. I alread added the print button, the path url and so on and it will create a pdf file for me. What I am not able to do is to access the forms cleaned_data from my BaseAdmins (extends the ModelAdmin) class like this: form = BaseForm(request.POST) if form.isValid(): data = form.cleaned_data It will just give me random kinds of errors, like object has no attribute 'is_bound' So I think that I am generally wrong with the context where I am trying to get the cleaned_data from the form. Every tutorial I found is just showing how to get the data but not fully resolved if it contains foreign keys and not … -
Model constraints are not working with Faker ( Django )
I am just starting to use pytest and faker for testing while trying to create text for a field in testing db the constraints are being ignored and i don't know how to fix it. models.py from django.db import models # Create your models here. class Note(models.Model): body = models.TextField(null=True, blank=True, max_length=5) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] factories.py import factory from faker import Faker fake = Faker() from mynotes_api.models import Note class NoteFactory(factory.django.DjangoModelFactory): class Meta: model = Note body = fake.text() conftest.py import pytest from django.contrib.auth.models import User from pytest_factoryboy import register from tests.factories import NoteFactory register(NoteFactory) @pytest.fixture def new_user1(db, note_factory): note = note_factory.create() return note test_ex1.py import pytest def test_product(new_user1): note = new_user1 print(note.body) assert True test output the problem as visible in output is that the length of the text generated and being stored in the testing db is more than 5. kindly guide me in this regard. -
How to create relationships between 3 models in django?
I'm building a marketplace that have 2 user types i.e. buyers and sellers. Now I want to create a relationship model between buyers, sellers and OrderedItems, so that the sellers gets notified once the buyers orders an item. This is the model I made: class Ordered(models.Model): ordered_items = models.ManyToManyField(Cart) seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True) buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE) ordered_on = models.DateTimeField(auto_now_add = True) But I don't know how to implement this in views.py Any suggestion will be really helpful Thank you -
passing values from one function to another in django
I am creating an app in which I have to transfer value from one function to other in Django, after reading some articles I have found out I can use global functions inside the Django function. I just want to ask is it good to use global function because the app I am wokring on is gonna be live and people will use it I dont want any trouble at later stages. -
Filter is not working properly in Django REST Framework
This is my TestViewSet. class TestViewSet(ListAPIView, CreateAPIView, UpdateAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination serializer_class = TestSerializer model = Test create_class = CreateTestSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['department__name', 'code', 'billing_category__id', 'billing_category__name'] def get_queryset(self): name_str = self.request.query_params.get("name") department_id = self.request.query_params.get("department_id") pk = self.kwargs.get("id") self.pagination_class.page_size = page_size if name_str is not None: return self.model.objects.filter( Q(name__icontains=name_str) | Q(name__iexact=name_str) | Q(name__istartswith = name_str) ) elif pk is not None: return self.model.objects.filter(id=pk) elif department_id is not None: return self.model.objects.filter(department_id=department_id) else: return self.model.objects.all() name is CharField and department is ForeignKey in Test Model. When i am passing this url - http://127.0.0.1:8000/api/v1/package/test/?name=fun&department_id=7 It is ignoring deparment_id. I just don't know why. Individually both are working fine. I'm wondering why it is ignoring deparment_id ? Thank you !! -
MiddlewareMixin missing required argument: 'get_response' django
Does anyone have any ideas on why I am getting this error? My program was working before and I don't know what I changed to cause it to break. My main website works but whenever I make this get request to http://10.0.0.233:8000/watcher/form/list I get the error below. I searched my whole project and did not find MiddlewareMixin used anywhere. urls.py: from django.urls import path from . import views urlpatterns = [ path('form/list',views.get_all_form_items), ] Views.py @api_view(['GET']) def get_all_form_items(request): snippets = form_item_db.objects.all() serializer = form_item_db_serializer(snippets, many=True) return Response(serializer.data) Error: Django version 4.0, using settings 'backend.settings' Starting development server at http://10.0.0.233:8000/ Quit the server with CTRL-BREAK. [05/Jan/2022 02:11:55] "GET /watcher HTTP/1.1" 200 644 [05/Jan/2022 02:11:55] "GET /static/js/main.1924b030.js HTTP/1.1" 304 0 [05/Jan/2022 02:11:55] "GET /static/css/main.31d6cfe0.css HTTP/1.1" 304 0 Internal Server Error: /watcher/form/list Traceback (most recent call last): File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 493, … -
how to show multiple image objects in django template?
models.py class ProductVariantsImages(DateTimeModel): product_variant = models.ForeignKey(ProductVariants, on_delete=models.CASCADE, related_name='product_variants_images') variant_images = models.ImageField(upload_to='uploads/') def __str__(self): return str(self.id) HTML <div class="input-group"> {{variant_images}} </div> views.py @login_required def item_approval(request, pk): if request.method == "GET": product_form = AdminProductForm(request.POST) item = ProductVariants.objects.get(item_num=pk) variant_images = ProductVariantsImages.objects.filter(product_variant=item) print(variant_images) product_form = AdminProductForm(instance=product) item_form = ProductVariantsForm(instance=item) variant_images = ProductVariantsImagesForm(instance=product_variant_images)# here I get multiple objects print(variant_images) return render(request, 'loom_admin/product_details.html', {'item_form':item_form, 'product':product, 'product_form':product_form, 'variant_images':variant_images, }) while running I get 'QuerySet' object has no attribute '_meta' when I put variant_images = ProductVariantsImagesForm(instance=product_variant_images[0]) the error disappear. But I am getting first image object. What if I want to do to get multiple images that related to the filter query in django template? -
Drf: returns 403 instead of 401 after jwt token expires?
"DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], I am using session authentication for django admin and swagger and jwt for rest of the part. The issue is I am getting 403 after token expires but I think it should return 401 since the error is Given token not valid for any token type. Or 403 is the correct response ? -
Django migrations, calculate new fields value based on old fields before deleting old fields?
We are intenting to rework one of our models from old start-end date values to use starting date and length. However, this does pose a challenge in that we want to give default values to our new fields. In this case, is it possible to run migration where we create new field, give it a value based on models old start-end fields from django.db import models class Period(models.Model): #These are our new fields to replace old fields period_length=models.IntegerField(default=12) starting_date=models.DateField(default=Date.today) #Old fields. We want to calculate the period length based on these before we remove them start_day = models.IntegerField(default=1) start_month = models.IntegerField(default=1) end_day = models.IntegerField(default=31) end_month = models.IntegerField(default=12) Starting months and ending months can be anywhere between 1 and 12, so we need to run bunch of calculations to get the correct length. Is there a way for us to run a function in migrations that, after adding the new fields, calculates their new values before calling for removal of the old fields? I do know I can create basic add/remove fields with makemigrations, but I want to add the value calculations in between. Other option I have considered is to first run a migration to add the fields, then a … -
Any specific reasons why one should use `update_or_create` in Django?
So I have been using Django models' update_or_create function to upsert rows in a model. Wanted to ask, except the transaction being atomic, are there any added benefits? We can always do a = Models.objects.get(id=21) a.some_field = 'new_value' a.save() -
My Django project use Stripe payment gateway. how to remove billing address
I am used Stripe payment gateway for get payment but checkout page get Billing address fields. how to remove this fields. checkout page Hear is my code: checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": "order", }, "unit_amount_decimal": 5 * 100, }, "quantity": 1, }, ], customer_email="test@gmail.com", mode="payment", success_url=success_url, cancel_url=cancel_url, ) -
Make Django ListView display horizontal rather than vertical
I just started learning Django and I'm trying to display some blogs while following the tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction. I have a list view class (shown below). However, the elements appear one after the other on seperate lines. Is there any way I can fix this so, say, three elements appear on one line? I tried using #all-blogs { display: inline-flex; } but this makes everything appear in one line. Here is my code. ListView Class: class BlogListView(generic.ListView): model = Blog context_object_name = 'all_blogs' paginate_by = 15 blog_list.html <div id="all-blogs"> {% for blog in all_blogs %} <div class="blog"> <a href="{{ blog.get_absolute_url }}"> <h1 class="blog-title">{{ blog.title }}</h1> <h1 class="blog-author">By: {{blog.author}}</h1> <p class="blog-published">{{blog.published}}</p> <p class="blog-description">{{blog.description}}</p> </a> </div> {% endfor %} </div> Any help is appreciated. Thanks in advance -
how to specify search_filter='(objectClass=group)',search_scope='SUBTREE',attributes = ['member']) for django python3 ldap
I am using django python3 ldap package to sync some users from ldap server to my django application. Its getting connected to ldap server with my configurations defined in settings but user lookup is failed. The search base that i am using is LDAP_AUTH_SEARCH_BASE = "CN=SOME_USERS,OU=Security Group,OU=Example,DC=Example,DC=com" But I get my result with a different package named ldap3. for ldap3 I can specify some extra parameters along with search_base like below from ldap3 import Server, Connection, SAFE_SYNC server = Server('my_server') conn = Connection(server, 'my_user', 'my_password', client_strategy=SAFE_SYNC, auto_bind=True) conn.search(search_base='CN=DTS_USERS,OU=Security Group,OU=Viacom18,DC=viacom18,DC=com',search_filter='(objectClass=group)' ,attributes = ['member']) I just want to know how can I specify "search_filter='(objectClass=group)' ,attributes = ['member']" with django python3 ldap. I checked the documentation at https://github.com/etianen/django-python3-ldap but could not find any helpful thing. Any help will be appreciated? -
Celery workers stop receiving tasks after a certain period without any error
I'm using Celery beat and workers for task scheduling in a Django project. Redis is being used as the broker. I've daemonized it with systemd. Django project settings for Celery # Celery application definition CELERY_BROKER_URL = "redis://localhost:6379" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_TIMEZONE = "UTC" CELERY_MAX_TASKS_PER_CHILD = 1 CELERY_IGNORE_RESULT = True # Celery periodic task schedule CELERY_BEAT_SCHEDULE = { "task-1": { "task": "project.apps.app1.tasks.task_no_1", "schedule": datetime.timedelta(seconds=5), }, "task-2": { "task": "project.core.tasks.task_no_2", "schedule": datetime.timedelta(seconds=10), }, "task-3": { "task": "project.apps.app1.tasks.task_no_3", "schedule": datetime.timedelta(seconds=10), }, "task-4": { "task": "project.apps.app1.tasks.task_no_4", "schedule": datetime.timedelta(seconds=5), }, "task-5": { "task": "project.apps.app1.tasks.task_no_5", "schedule": datetime.timedelta(seconds=10), }, "task-6": { "task": "project.apps.app1.tasks.task_no_6", "schedule": datetime.timedelta(seconds=30), }, "task-7": { "task": "project.apps.app1.tasks.task_no_7", "schedule": datetime.timedelta(seconds=30), }, } /etc/default/celeryd # Name of nodes to start CELERYD_NODES="worker1 worker2" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/adnan/project/env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="project.core" # How to call manage.py CELERYD_MULTI="multi" CELERYD_USER="adnan" CELERYD_GROUP="www-data" CELERYD_LOG_LEVEL="INFO" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" # Options for Celery Beat … -
Gunicorn, nginx, django, inside of a docker container. Gunicorn successfully runs on port 80 but nginx fails
I'm trying to set up a simple blogging site that I wrote using the django framework. The website works except that it isn't serving static files. I imagine that's because nginx isn't running. However, when I configure it to run on any port other than 80 I get the following error: nginx: [emerg] bind() to 172.17.0.1:9000 failed (99: Cannot assign requested address) When I run it on a port that is already being used by gunicorn I get the following error: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) My nginx configuration file is as follows: upstream django { server 127.0.0.1:8080; } server { listen 172.17.0.1:9000; server_name my.broken.blog; index index.html; location = /assets/favicon.ico { access_log off; log_not_found off; } location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django admin: "How to properly display multi-layered relations?"
I'm new to Django framework and trying to build a math test application. Idea is to generate a test from a pool of questions. I have a following DB entities: class TestResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'test_results' class Question(models.Model): text = models.CharField(unique=True, max_length=255) type = models.IntegerField(blank=True, null=True) class Meta: db_table = 'questions' class Answer(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) text = models.CharField(max_length=255) is_correct = models.BooleanField() class Meta: db_table = 'answers' class AskedQuestion(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) test = models.ForeignKey('TestResults', on_delete=models.CASCADE) class Meta: db_table = 'asked_questions' class GivenAnswer(models.Model): answer = models.ForeignKey(Answers, on_delete=models.CASCADE) test = models.ForeignKey(TestResults, on_delete=models.CASCADE) class Meta: db_table = 'given_answers' I am able to display AskedQuestion and GivenAnswer as 2 separate StackedInline for TestResult. But I want to display Question + Answer pairs when I navigate to TestResult page in Django admin. Any suggestions would be appreciated.