Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Are django abstract models really that useful?
I have recently come across this in one of django related blog post! class Client(models.Model): name = models.CharField(max_length=255, required=True) # .. other fields class Meta: abstract = True After reading the docs I couldn't understand what the purpose of "abstract = True" is. Any help will be useful. Thanks! -
django web app deployment on windows 10 using apache server(WAMP) not displaying CSS for admin site
On Windows 10 django app when run using development server by using command python manage.py runserver shows admin login page and admin site correctly. but if same django app at same path when served using apache is not displaying css correctly for admin login and other admin site pages. I have tried to follow steps at https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/modwsgi/ but some configuration/setting is missed/incorrect resulting in css not applied to admin login page and admin site. my development and deployment is on same windows 10 computer with WAMP server 3.2.3.3. I have installed mod_wsgi and following are relevent section from settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secrete key is listed here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
xlsx file not being exported django rest framework
I am calling ajax request from frontend to export data in excel sheet. js function exportData(){ create_spinner("Please wait while we export data."); var agent = $("#agent").val() var dateRange = $("#dateRangeValue").val() var queue = $("#queue").val() var direction = $("#direction").val() var department = $("#department").val() var serviceLevel = $("#sl").val() $.ajax({ type: 'POST', url: "/call-record-api/export-data/", data: { "agent": agent, "dateRange": dateRange, "queue": queue, "direction": direction, "department": department, "serviceLevel": serviceLevel, }, success: function(resultData) { console.log("success"); hide_spinner(); }, error: function (err) { console.log("AJAX error in request: " + JSON.stringify(err, null, 2)); create_spinner("Couldn't export data. Please try again"); setTimeout(function(){ hide_spinner()}, 1000); } }); } I have gone through documentation and implemented the same. urls.py url(r'^call-record-api/export-data/$', ExportCallRecordView.as_view({"post":"list"})), views.py class ExportCallRecordView(XLSXFileMixin, ReadOnlyModelViewSet): def get_queryset(self): calls = export_customized_calls(self.request) print(calls.count()) return calls serializer_class = CallRecordSerializer renderer_classes = [XLSXRenderer] filename = 'call_record_export.xlsx' But i cannot see the file getting downloaded. However i can see success in browser console. -
How to perform multiple insertion using django rest viewsets?
I'm working on this api where a user can select multiple languages and can mark the proficiency in each language. The model is as follows. class UserLanguage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) proficiency = models.DecimalField(max_digits=4, decimal_places=2) class Meta: db_table = "user_language" Serializer looks like: class UserLanguageSerializer(serializers.ModelSerializer): class Meta: model = UserLanguage fields = '__all__' I have done the views as follows class UserLanguageViewSet(viewsets.ModelViewSet): queryset = UserLanguage.objects.all() serializer_class = UserLanguageSerializer The code works fine for a request like { "proficiency": "04.00", "user": 1, "language": 1 } I want the api to accept a list like this: [ { "proficiency": "05.00", "user": 1, "language": 1 }, { "proficiency": "04.00", "user": 1, "language": 1 }] For each item in the list I want to create a new row in 'user_language' table. Am I doing it the right way? If not show me the right way. How should I modify my models, serializer or view to attain this? I don't know if the above request is in the right format. If not please let me know. Thank you. -
DRF: SearchField for custom queruset
I have get_queryset() overrited method in my ModelViewSet class - it return qureyset with filter by user. So i need implement a SearchFilter search not only in queryset, returned by get_queryset method (Follow.objects.filter(following=self.request.user)), but in all values from model - in Follow.objects.all() There is my class: class FollowViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): queryset = Follow.objects.all() serializer_class = FollowSerializer filter_backends = (filters.SearchFilter,) search_fields = ("user__username", "following__username") def perform_create(self, serializer: Serializer) -> Follow: following = self.request.data.get("following") if not following: raise ParseError( detail="following must be transfered", code=status.HTTP_400_BAD_REQUEST, ) if self.request.user.get_username() == following: raise ParseError( detail="User cant follow himself", code=status.HTTP_400_BAD_REQUEST, ) return serializer.save(user=self.request.user) def get_queryset(self) -> QuerySet: return Follow.objects.filter(following=self.request.user) -
Best way to display a field site-specific using the Django Sites framework
I'm currently using the Django Sites framework with two sites. I have a model called Product, and I only want to display the product price on one of the sites. How could i achieve this in the Django admin? I'm currently using a many-to-many relationship on the display_price field, but it feels somewhat "dodgy". My code: class Product(models.Model): name = models.CharField( _('Product name'), max_length=255, unique=True ) ... display_price = models.ManyToManyField( Site, related_name='display_price_product_site', blank=True ) ... sites = models.ManyToManyField( Site, related_name='product_site', blank=True ) objects = models.Manager() on_site = CurrentSiteManager() -
How to load data without using a form
I am a student learning Django. I've been loading data using form so far, but I'd like to know how to load data when I press the button without using form. Is there something wrong with my code? model.py class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.join_code) class Meta: ordering = ['join_code'] Join/views from datetime import timezone from django.shortcuts import render Create your views here. from zeronine.models import * def join_detail(request): product = Product.objects.all() if request.method == "POST": join = Join() join.product_code = product join.username = request.user join.part_date = timezone.now() join.save() return render(request, 'zeronine/detail.html', {'product': product}) detail.html {% extends 'base.html' %} {% block title %} 상품 상세보기 {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-4"> <img src="{{product.image.url}}" width="190%" style="margin-top: 35px;"> </div> <div class="text-center col" style="margin-top:150px; margin-left:200px;"> <b><h4 class="content" style="margin-bottom: -5px;"><b>{{product.name}}</b></h4></b> <br> <div> <!-- <span>주최자 : <b>{{ product.username }}</b></span><br>--> <span style="color: #111111">모집기간 : <b>{{ product.start_date }} ~ {{ product.due_date }}</b></span> </div> <hr style="margin-top: 30px; margin-bottom: 30px;"> <p><span class="badge badge-dark">가격</span> {% load humanize %} {% for designated in designated_object %} {% if designated.product_code.product_code == product.product_code %} {{designated.price | floatformat:'0' | intcomma }}원 {% … -
Page or Form Not showing validation Error Django
Hello Guys I'm trying to show validation errors on Django forms. I do not know what's going on. I want to make a validation error if the username already exists in the database, but it ain't throwing me an error. Here is My code. In terminal its show the error but not in the page. Forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.forms import fields from django.forms.widgets import PasswordInput User = get_user_model() unallowed_username = ['hello'] class LoginForm(forms.ModelForm): username= forms.CharField() password = forms.CharField( widget=PasswordInput( attrs={ "class": "login-password form-control", "id": "login-password" } ) ) class RegisterForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField() username = forms.CharField() password1 = forms.CharField( label="Password", widget=forms.PasswordInput( attrs = { "class": "form-control user-password1", "id": "user-password" } ) ) password2 = forms.CharField( label="Confirm Password", widget=forms.PasswordInput( attrs = { "class": "form-control user-password2", "id": "user-confirm-password" } ) ) class Meta: model = User fields = ["first_name", "last_name","username", "email", "password1","password2"] def clean_username(self): username = self.cleaned_data["username"] qs = User.objects.filter(username__iexact = username) if username in unallowed_username: raise forms.ValidationError("This username is unproper Username Please pick another") if qs.exists(): print("invalid username") raise forms.ValidationError(("This is an Invalid Username Please pick another")) return username def clean_email(self): email = self.cleaned_data["email"] … -
How do I run some code when a user signs up with python-social-auth in Django?
I'm using Django and python-social-auth and when a user signs up I want to call the API of another service to add the user to it (think something like Mailchimp). What's the correct way of doing it? My app has a backend which is API only written in Python and Django, and a frontend written in JavaScript. For the purpose of signing up/in though, there's a link to the backend (api.example.com/social-auth/...) so it ends up being a bit of a hybrid. After logging in or out, the backend redirects the user back to the frontend, by having this in settings.py: LOGIN_REDIRECT_URL = env("FRONTEND_URL") LOGOUT_REDIRECT_URL = env("FRONTEND_URL") If there's any of my code that's relevant to this question, please let me know and I'll add it. I'm not sure what parts are and I didn't want to do a big dump of all my code. Also, I don't think my code around this issue is particularly good, so I'm happy to change it. -
I trial make Permission in CreateView
I want to check if user in true editUser before open url and create post, urls.py", line 13, in path('new/', PostCreateView.as_view(), name='new_post'), AttributeError: 'NoneType' object has no attribute 'as_view' def notLoggedUsers(view_func): def wrapper_func(request,*args,**kwargs): if not request.user.profile.editUser: return redirect('index') else: return view_func(request,*args,**kwargs) return wrapper_func @notLoggedUsers class PostCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'crud/new_post.html' form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Send emails with django send_mass_mail
I am trying to send two different emails using the django send_mass_mail function. I'm very new to django, and I'm struggling to get it to work. The send-Mail function works fine when I use it, but I want to send different emails to the customer and the site owner when a purchase is made. Any help with this would be amazing! Thanks so much! def _send_confirmation_email(self, order): """ Send the user a confirmation email """ cust_email = order.email subject = render_to_string( 'checkout/confirmation_emails/confirmation_email_subject.txt', {'order': order}) body = render_to_string( 'checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL}) subject2 = render_to_string('Order Placed', {'order':order}) body2 = render_to_string( 'An order has been placed', {'order': order} ) message1 = ( subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email] ) message2 = ( subject2, body2, settings.DEFAULT_FROM_EMAIL, ['test@hotmail.com'] ) send_mass_mail((message1, message2), fail_silently=False) -
how to change my flask app to django app?
I want to change my flask web to django app. from flask import Flask app = Flask(__name__) @app.route('/login', methods = ['POST']) def login(): try: data = request.json usernameval = data['userName'] passwordval = data['password'] response = {'username': usernameVal, 'password':passwordval} except Exception as error: response = {'error': 'Try again'} finally: return response if __name__ == '__main__': app.run(host="0.0.0.0",port=8080) I am using postman to sending request to this route abd want to do the same with django app. What is the django version of this code ? -
Assign username to field in models.py table
Let’s say I have a Table1 that contains 5 data, > class Table1(models.Model): > code = models.CharField(max_length=16,unique=True) > > author_Up = models.CharField(max_length=16,default=User) > date_Up = models.DateTimeField(auto_now=True) > post_date = models.DateTimeField(default=timezone.now) > author = models.ForeignKey(User,on_delete=models.CASCADE) > def __str__(self): > return self.code I am using formes.py as: class Table1_F(forms.ModelForm): code = forms.CharField(label='Code',max_length=16) class Meta: model= Table1 fields=['code'] The Problem is I need to assign a new values of (author_Up) and (date_Up) every time that another user make an update and keep the initial author. How do I solve this Please? -
updating the master records with detail records as per posting
I lost and do not know where to start and end. please light on this tunnel. I am having transaction model with data as follows: Acctcode acctname debit credit 1101 stationary exp 100.00 1101 stationary exp 245.00 I am having Account master model: code detail reportingacct Acct Level 1000 expenses 0 1 1100 office expenses 1000 2 1101 stationary exp 1100 3 I need data for context as: code name balance AcctLevel 1000 expenses 345.00 1 (posting from level 2) 1100 office exp 345.00 2 (posting from level 3 sum) 1101 stationary exp 345.00 3 (sum of two transaction) I tried with view as follows: acctbalance = FinTransDetail.objects.values("fd_acct__AcctCode", 'fd_acct__AcctName','fd_acct__AcctLevel','fd_acct__AcctReport1').order_by( 'fd_acct__AcctCode').annotate(balance=Sum('fd_debit')-Sum('fd_credit')) print (acctbalance) sample data with real value: ***<QuerySet [{'fd_acct__AcctCode': Decimal('1101'), 'fd_acct__AcctName': 'OFFICE BUILDINGS', 'fd_acct__AcctLevel': Decimal('3'), 'fd_acct__AcctReport1': '1100', 'balance': Decimal( '112')}, {'fd_acct__AcctCode':....."**** for data in acctbalance: print(data['balance']) sample data with real value: ***112 -2786 302 -500 100 230 2254 400 **** my models: class AccountMaster(models.Model): """Model representing a book (but not a specific copy of a book).""" AcctLevel = models.DecimalField(max_digits=1, decimal_places=0, default=1) AcctCode =models.DecimalField( decimal_places=0, max_digits=6,unique = True) AcctName = models.CharField(max_length=50) AcctDesc = models.CharField(max_length=100) AcctType = models.CharField(max_length=20,choices=ACCTTYPE_CHOICES,null=True, blank=True) AcctReport1 = models.CharField(max_length=20, null=True, blank=True, default=0) AcctReport2 = models.DecimalField(max_digits=6, decimal_places=0, default=0, blank=True) AcctPosting … -
Book object is not iterable: Trying to display similar objects of an instance based on a field
I am working on a library project that displays books and each both is in a category(history, math, adventure, etc). On the detailed view of a book, I want a link (with "See similar books in this category") that will redirect the user to other books of the same category of the current book. So if the detail page of a book has a category of "history", the link will direct to other books in the "history" category. The redirection is to another template (Addon: In helping me out, I would love to display the "similar books" in the same page, not a different page) error details TypeError at /search/similar/bootsrtap/ 'Book' object is not iterable models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) category = models.CharField(max_length=255, choices=choice_list) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.author + ": " + self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def similar_book(self): return Book.objects.filter(category=self.category) urls.py urlpatterns = [ path('detail/<slug:slug>/', BookDetail.as_view(), name='detail'), path('search/similar/<slug:slug>/', views.search_similar_results, name='search_similar_results'), views.py … -
How to put this button next to my form field and not two lines below?
Im trying to learn django so Im making a website, but I dont know much of Html, css, or js. so I used a wesite builder to make a template, and Im just editing the codes it gave me. This is the scenario Im trying to fix: Link to Problematic part's picture I want the yellow button to be next to the form field but I cant figure out how to get it there this is the corresponding part from my html file: <div class="u-align-left u-container-style u-layout-cell u-right-cell u-shape-rectangle u-size-30 u-size-xs-60 u-layout-cell-2" src=""> <div class="u-container-layout u-container-layout-5" src=""> <h2 class="u-align-center u-custom-font u-text u-text-default u-text-6">Add</h2> <p class="u-align-left u-custom-font u-heading-font u-text u-text-2"> <form method='POST' class='post-form'> {% csrf_token %} {{ forms.newcat.non_field_errors }} <div class="fieldWrapper"> {{ forms.newcat.name.errors }} <label for="{{ forms.newcat.name.id_for_label }}">New Category Name </label> {{ forms.newcat.name }} </div> <button type='submit' name='addcategory' class="u-btn u-btn-round u-button-style u-hover-palette-3-light-2 u-palette-3-light-1 u-radius-50 u-btn-1">Add</button> </form> </p> ps. I figured the issue is in the html parts, but if needed I can provide the css file too. Thanks in advance for the help! -
Build a proxy in Django that can handle concurrent requests
I'm looking to build a small proxy for myself in Django. The issue I have is that if I query one endpoint two times in parallel, it waits for one request to finish before serving the other one. I feel like this is not optimised because most of the time is spent waiting for the network to download the page. For my two requests this should be done in parralel, just like a lib like Scrapy would do. Do you have any insights on how to do this or am I missing something? Thanks! -
Display a chart of last 30 days-django
I am working on customer requests project where I want to visualize the requests submitted in the last 30 days on chart. This will sum up daily requests for the last 30 days. below is the code I have but the result is an empty chart: def daterange(date1, date2): for n in range(int ((date2 - date1).days)+1): yield date1 + timedelta(n) def summarychat(request): current_date = date.today() days_before = date.today()-timedelta(days=30) for dt in daterange(days_before,current_date): print(dt.strftime("%Y-%m-%d")) dates = Customer_Requests.objects.filter(arrival_date=dt) date_data = list() category = list() for i in dates: i =Customer_Requests.objects.values('arrival_date').annotate(re_number=Count('request_name')).order_by('arrival_date') date_data.append(int(i['re_number'])) category.append(i['arrival_date']) resolved_series = { 'name': 'Daily', 'data': date_data, 'color': 'green' } chart3 = { 'chart': {'type': 'column'}, 'title': {'text': 'Statistics'}, 'xAxis': {'date_data': date_data}, 'series': [resolved_series] } dump3 = json.dumps(chart3) return render(request,'summarized.html',{'chart3': dump3}) I want to transform this SQL query in python: SELECT count(request_name) from Customer_Requests where date between date1 and date2; here date1 is today's date and date2 is today'date-30 days Please assist on this. -
Django TestCase works with Sqlite3 - doesn't work with Postgres
I'm trying to figure out why my tests are working with Sqlite3 but don't work with Postgres. import os from django.conf import settings from django.test import TestCase from products.factory import ProductFactory from products.models import Product, Organisation from products.services.imports import ImportService from users.factory import UserFactory, OrganisationFactory from users.models import User class ProductTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: cls.org = OrganisationFactory.create(name='My organisation') cls.user = User.objects.create_user('peter','xxxxxxxx') cls.user.organisation = cls.org cls.product = ProductFactory.create(title='Title', created_by=cls.user, organisation=cls.org) def test_product_has_organisation(self) -> None: self.assertTrue(self.product.organisation, 'Product has no organisation') When running it with Postgres it raises: ERROR: test_product_has_organisation (products.tests.test_product.ProductTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/milano/PycharmProjects/.virtualenvs/markethelper_api/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.ForeignKeyViolation: insert or update on table "products_product" violates foreign key constraint "products_product_updated_by_id_33940c75_fk_users_user_id" DETAIL: Key (updated_by_id)=(19) is not present in table "users_user". The Product.updated_by: updated_by = CurrentUserField('users.User', on_delete=models.CASCADE, related_name='updated_products', null=True, blank=True, verbose_name='Updated by', on_update=True) Do you know where is the problem? -
Django-celery , "celery_file -A django_email_celery worker --loglevel=info" not working
I want use celery with RabbitMQ for email function for my Django - project , I Have installed celery and RabbitMQ. I hvae tried to Run this command but not working any of these. I am using Windows 10. enter image description here enter image description here enter image description here -
Django - Shared user database
I am having a project using a mother server gathering the data of a lot of small devices. The mother database is running Django,as well as the clients. The clients are mainly offline but go online to synchronize with the mother database from time to time. I would like to have a user management for my project. The idea is that all the changes of the users is happening on the mother database to avoid conflicts in the event both database are getting updated. I am not too sure about the approach to take. What are my different options and what would you recommend? -
Issue updating Django database
Hi everyone please I'm having difficulty updating data from the database base list. The editing page rendered but it doesn't show any input form. Hi everyone please I'm having difficulty updating data from the database base list. The editing page rendered but it doesn't show any input form. Views.py def edit_result(request, id): models = StudentResult result = Student.objects.get(id = id) return render (request,'studentportal/edit_result.html', {'result':result }) Models.py class Student(models.Model): userprofile = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE, related_name='myuser') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) profile_pic = models.ImageField(upload_to=student_image, verbose_name="ProfilePicture", blank=True) level = models.IntegerField() guardian_email = models.EmailField() guardian_phone = models.IntegerField() def __str__(self): return self.first_name def get_absolute_url(self): return reverse("studentportal:student_detail", kwargs={"pk": self.id}) class StudentResult(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='myresult') english = 'english' mathematic = 'mathematic' physic = 'physic' chemistry = 'chemistry' computer = 'computer' agric = 'agric' subject = [ (english, 'english'), (mathematic, 'mathematic'), (physic, 'physic'), (chemistry, 'chemistry'), (computer, 'computer'), (agric, 'agric'), ] subject = models.CharField(max_length=50, choices=subject) # subject = models.CharField(max_length=50) exam = models.IntegerField() test = models.IntegerField() total = models.IntegerField() def __str__(self): return self.subject Forms.py class StudentModelForm(forms.ModelForm): class Meta: model = Student fields = ('userprofile','first_name','last_name','profile_pic','level','guardian_email','guardian_phone') class ResultModelForm(forms.ModelForm): class Meta: model = StudentResult fields = ('student','subject','test','exam','total') -
how to get correct attribute for class Meta?
after running command python manage.py inspectdb, i am having following error TypeError: 'class Meta' got invalid attribute(s): ifsc,bank,branch,address,city,district,state my model is as following from django.db import models class Banks(models.Model): class Meta: db_table = 'banks' name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'branches' ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey('Banks', models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address= models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) -
How to store picture password in database using Django framework?
when I click one of the picture of the image, how will it be stored in the database -
How to fetch data from another app Django
I'm creating a quiz project using Django with MongoEngine. Multiple Choice Questions and quiz are two separated apps. I want to fetch multiple choice in quiz based on m_id (unique number for each multiple choice). I'm a beginner and need a little help. How can i achieve thisMCQS Model from django_mongoengine import Document, EmbeddedDocument, fields class multichoice(Document): m_id = fields.IntField(min_value=1, verbose_name='MCQ Id') m_title = fields.StringField(primary_key=True, max_length=255, verbose_name='Title') m_question = fields.StringField(verbose_name='Question') m_alternatives = fields.ListField(fields.StringField(),verbose_name='Alternatives') def __str__(self): return self.m_title Quiz Model from django_mongoengine import Document, EmbeddedDocument, fields from mcqs.models import * class quiz(Document): q_id = fields.IntField(min_value=1, verbose_name='Quiz ID') q_title = fields.StringField(primary_key=True, max_length=255, verbose_name='Title') q_s_description = fields.StringField(max_length=255, verbose_name='Description') q_questions = fields.ListField(fields.IntField(), verbose_name='Question Numbers', blank=True) def __str__(self): return self.q_title MCQ Views def view_multichoice(request, m_id): get_md = multichoice.objects(m_question_number = m_id) return render(request, 'mcqs/mcq.html', {'get_md':get_md}) Quiz Views def view_quiz(request, q_id): get_q = quiz.objects(q_id = q_id) return render(request, 'quiz/quiz.html', {'get_q':get_q}) Current Result Expected Result