Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url (slug)
The question is, I have a mini-blog, there are articles and user profile (pages). I display articles at site/articlename I want to display the user account at site/username views.py (article): def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'post_detail.html', {'post': post }) views.py (profile users): class UserProfileView(DetailView): template_name = 'users/profile/profile-user-view.html' queryset = User.objects.all() def get_object(self): username = self.kwargs.get("username") return get_object_or_404(User, username=username) URL's: path('<str:username>', UserProfileView.as_view(), name='user_detail') path('<slug:slug>', views.post_detail, name='post_detail') Now my user profile opens at site/username, but the article does not open at site/article name. I suspect some kind of conflict in the URL (slug). How can I make it so that both articles and an account at the site / address are opened without additional directories. I would be grateful for any help. -
Methode() got multiple values for argumen 'name'
i trying to do Django3 by example online shop => cart section and i tried this for my cart View @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(MainProduct, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product, quantity= cd['quantity'], override_quantity=cd['override'], color = cd['color'], size = cd['size'], ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) and this for cart.py that handle my cart requests class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self,color,size, product,quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ # self.cart['color'] = color # self.cart['size'] = size product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price), 'color' : str(colors), 'size': str(sizes) } if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() and i have this Error Exception Value: add() got an unexpected keyword argument 'colors' but when i ignore color and size that will work with no Error ... -
i am not able to render my urls in my template it gives me error rendering
NoReverseMatch at / Reverse for 'Jersey' with no arguments not found. 1 pattern(s) tried: ['Jersey/(?P[^/]+)/$'] Below is the code to my views.py class JerseyView(TemplateView): #paginate_by=3 template_name='Ecommerce/Jersey.html' def get_context_data(self, **kwargs): et =super(JerseyView, self).get_context_data(**kwargs) et['United']= Item.objects.filter(category="3").filter(subcategory="9") et['Chelsea']= Item.objects.filter(category="3").filter(subcategory="10") return et below is the code for my urls.py path('Jersey/<slug>/', JerseyView.as_view(), name="Jersey" ), I called This link in my Navbar as <a class="dropdown-item" href="{% url 'Ecommerce:Jersey' %}">Men's Clothing</a> when I click on it it gives me the error as NoReverseMatch at / Reverse for 'Jersey' with no arguments not found. 1 pattern(s) tried: ['Jersey/(?P[^/]+)/$'] I don't know if there's something i am missing out because i have checked my spelling and still getting the same error -
Update field in db in django from views with existing form, won't update because of "Integrity Error"
My first post, really newbie at programming. I am having issues to update a field in a form. I'll try to explain my best. I have a Catalog class (products or services) with a couple fields, 2 of them must be unique. models.py class Catalogo(models.Model): item = models.CharField( max_length=100, help_text="Product or service name", unique=True ) sku = models.CharField(max_length=50, help_text="Part Number", unique=True) category = models.CharField( max_length=15, choices=categoria, verbose_name="Category" ) description = models.CharField( max_length=200, help_text="Item description", verbose_name="Descripción", ) created = models.DateTimeField(auto_now_add=True, help_text="Created") updated = models.DateTimeField(auto_now_add=True, help_text="Updated") active = models.BooleanField(default=True) class Meta: verbose_name = "product and service" verbose_name_plural = "products and services" def __str__(self): return self.item Then i have a form to gather the information forms.py categories = [("Product", "Product"), ("Service", "Service")] class NewProductForm(forms.Form): item = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), label="Item", max_length=100, ) sku = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), label="Part number", max_length=50, ) category = forms.ChoiceField( choices=categories, label="Category", ) description = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}), label="Item description", ) Now for the views...i created 2 functions, one for adding new product/service and one for updating views.py def new_prod_serv(request): new_form = NewProductForm() if request.method == "POST": new_form = NewProductForm(request.POST) if new_form.is_valid(): new_product = Catalogo( item=new_form["item"].value(), sku=new_form["sku"].value(), category=new_form["category"].value(), description=new_form["description"].value(), ) new_product.save() return redirect("products-services") else: print(new_form.errors) context = {"formulario": new_form} … -
Errors while reloading Django project
In my Django project, which I run from batch file in Cmd, I get the following errors after I update the code and the code is reloading, which crashes my cmd and causes an exit from it: ** On entry to SGEBRD parameter number 10 had an illegal value ** On entry to SBDSVDXSafe MinimumPrecisionEpsilon parameter number 2 had an illegal value What is the meaning of these two lines? And how to prevent my code from crashing? -
Add extra fields to django form depending on another field value
I have a model 'Project' that is supposed to take multiple installment percentages of the total project cost. For example, if total cost of the project is $100, there can be four or five or as many installments are set. So one field is 'num_installment' = 4 (say). Now each installment can have different percentages of total cost (eg, 50,30,10,10 or any such combination). The problem is, since we don't know the number of installments prior to the form validation, the installment percentage fields can't be set before hand. So we need a dynamic form where four (or n number of) installment fields are popped up according to the num_installment field value. The Project model- class Project(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) net_charge = models.FloatField(null=True) num_isntallment = models.IntegerField(null=True) installments = ?????? -
two url django (slug and username)
I have a small blog, there was a little problem. I have articles and I have user profiles. I want articles to open at: http://127.0.0.1:8000/namearcticle There are user profiles, I want them to open at: http://127.0.0.1:8000/username My views article views.py: def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'post_detail.html', {'post': post }) My views UserNameProfile views.py: : class UserProfileView(DetailView): template_name = 'users/profile/profile-user-view.html' queryset = User.objects.all() def get_object(self): username = self.kwargs.get("username") return get_object_or_404(User, username=username) URL's: path('<str:username>', UserProfileView.as_view(), name='user_detail'), path('<slug:slug>', views.post_detail, name='post_detail'), Now when trying to open the article, the error is: Page not found (404) Request URL: http://127.0.0.1:8000/testarcticle Raised by: users.views.UserProfileView No User matches the given query. Although the user page opens. The question is, how can I make it so that I can open user profiles at the article address? site/username site/article -
Can't create the same object in Django HTML
I need to create 4 objects like the first one. But the second and the next iterations create objects under the first. Looks like there must be one more in the cycle. But doesn't. tamplate {% extends "main/base.html" %} {% block content %} <div class="row"> {% for item in articles %} <div class="col-md-12"> <div class="card mb-3" style="max-width: 540px; color: #212529"> <div class="row no-gutters"> <div class="col-md-4"> <img src="link" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title"><a href={% url 'articles-detail' item.id %}> {{ item.title | safe }}</a></h5> <p class="card-text">{{ item.content | safe | slice:":255" }}...</p> <p class="card-text"><small class="text-muted">{{ item.pub_date | date:"d-m-Y H:i" }} | {{ item.author }}</small></p> </div> </div> </div> </div> </div> {% endfor %} </div> {% endblock %} how it looks on the web-site -
Entries not showing up in the django table
Problem: I have got one contact model. In this contact model, I`ve got severals type (supplier, Customer and Employee). The data has been uploaded in the SQL table but it is not showing up in Django/html table. Do I need to change the way how my model is written? Thanks in advance Model: class Contact(models.Model): CONTACT_TYPE = ( (0, 'Customer'), (1, 'Supplier'), (2, 'Employee'), ) GENDER = ( (0, 'Male'), (1, 'Female'), ) type = models.IntegerField(choices=CONTACT_TYPE,default=1) gender = models.IntegerField(choices=GENDER,default=0) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Views: def index_supplier(request): contacts = Contact.objects.all() suppliers = Contact.objects.filter(type=1).all() count_supplier= Contact.objects.filter(type=1).count() context = { 'contacts': contacts, 'count_supplier': count_supplier, } return render(request, 'contacts/index_supplier.html', context) Templates: <div class="container-fluid"> <div class="col-sm-20"> <table id="dtBasicExample" class="table table-striped table-hover"> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script> <script> $(document).ready(function(){ $('#dtBasicExample').DataTable(); }); </script> <thead> <tr> <th>Type</th> <th>Contact Name</th> <th>Company</th> </tr> </thead> <tbody> {% for contact in suppliers.all %} <tr> <td>{{ contact.get_type_display }}</td> <td>{{ contact.first_name }}</td> <td>{{ contact.company }}</td> </tr> {% endfor %} </div> </div> -
OSError: [Errno 9] Bad file descriptor, every command for python
**every command are fail. i cannot run any command. it show OS error** -
Provide different pricing/ product information depending on logged in user in Django
I am building an ecommerce site in Django that is intended for B2B (business to business) and B2C (business to consumer) transactions. Regarding B2C, I could store the retail price in the databse. However, regarding B2B, the price can take on many values (infinite options). The pricing structure depends on some real-world agreements between the businesses. So the Supplier can create "Pricing Policies". This would require providing different pricing through different markup and margins on the product cost (cost stored in the database), or provide different shipping/ tax cost structures depending on the user account location. It could entail providing different discounts on the retail price according to the volume of sales on that business account. I imagined that the Supplier can create pricing policies (through some PricingPolicy model) and when the Business Customer logs in, they would see their relevant prices. It is not practical to store a different price for each product for every Business Customer in the database. How would one implement different pricing depending on the logged in user account? -
My Django minutes being read reads as month?
Hi so I've been developing a countdown timer account, and I made a code like the following (following a tutorial): {% for time in timer %} <p id="tm" style="margin-top:-8px;margin-bottom:20px;display:none;">{{time.time|date:"M d, Y H:m:s"}}</p> {% endfor %} I have set the timer in the clock widget to 03:50 but when I console.log via javascript const timeLength = documents.getElementById('tm'); console.log(timeLength.textContent) It prints 03:12, always been read as month instead of minutes. But the minute is always set to be read as month, And I am already sure that M (uppercase) supposed to represent month, and the m (lowercase) represents the minute, right?? Where did I go wrong? I have been stuck here for days, and from the research on google I have done, always said that M is month, and m is minute.. Thank you in advance. -
How to import Weazyprint properly
I am trying to import Weazyprint but it is not working for some reason, I have followed the instructions from: https://pypi.org/project/WeasyPrint/ https://weasyprint.readthedocs.io/en/latest/install.html#step-5-run-weasyprint but still nothing is working, I am using Pycharm and it is showing underlined error: No module named weasyprint I have python -m pip install WeasyPrint but it doesn't seem to be reading it, although when I try to reinstall it an error saying it is already satisfied Here is the views.py import weasyprint @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order,ordered=True, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0]+ '/css/bootstrap.css')]) return response My question: How to properly install it so that it can be recognized? Is there a way to install it through conda to be installed in my virtual environment? -
Cannot assign "('1',)": "Booking.package" must be a "Package" instance
I am trying to access my package key in my another model this is in my models.py class Booking(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,null=True) and i am trying to access my package id in package like this booking = Booking() booking.package = id booking.save() but it gives me this error on my template Cannot assign "('1',)": "Booking.package" must be a "Package" instance. -
How to prevent multiple form submissions in Django from server?
Is there a robust way to prevent multiple submissions from server-side? I am aware of the JS solution but I require a server-side solution for peace of mind. -
Django Admin: How to list related objects and add custom attributes
I have the models Lecture and Student in a online homework submission system. Students can be enrolled in lectures, where they can achieve points. The Lecture model has a method called get_grade(self, student) that calculates the current student grade. I would like to have a custom admin page, where all students enrolled in a specific lecture are listed, along with their grade in that lecture. Is there a way to add custom attributes when using list filters? I would like to avoid inlines on the Lecture modifiy page, since the grade calculation takes a while (scanning all the submissions for every student and exercise, selecting the maximum value, summing it up, computing the grade using a grading scale). -
Cant get many to many object in Django-Rest Framework
I am creating a basic restaurant management app using Django-Restframework. I have following models and serializers. Here is my models: from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5,decimal_places=2) photoUrl = models.URLField(blank=True) category = models.CharField(max_length=50) details = models.CharField(max_length=250) class Restaurant(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=250) logoUrl = models.URLField(blank=True) class Menu(models.Model): restaurant = models.OneToOneField(Restaurant, on_delete=models.CASCADE,primary_key=True,) name = models.CharField(max_length=100) products = models.ManyToManyField(to=Product,blank=True,related_name='menus') class Customer(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Order(models.Model): Oproducts = models.ManyToManyField(to=Product,blank=True,related_name='orders') customer = models.OneToOneField(Customer,on_delete=models.CASCADE) restaurant = models.OneToOneField(Restaurant,on_delete=models.CASCADE) issueTime = models.DateTimeField(auto_now_add=True) And these are my serializers: from rest_framework import serializers from django.contrib.auth.models import User from .models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') class ProductSerializer(serializers.ModelSerializer): class Meta : ordering = ['-id'] model = Product fields = ('id','name','price','photoUrl','category','details','menus','orders') extra_kwargs = {'menus':{'required':False},'orders':{'required':False}} class MenuSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True,read_only=True) class Meta: ordering = ['-id'] model = Menu fields = ("restaurant","name","products") extra_kwargs = {'products':{'required':False}} class RestaurantSerializer(serializers.ModelSerializer): menu = MenuSerializer(read_only= True) class Meta: ordering = ['-id'] model = Restaurant fields = ("id","name","address","logoUrl","menu") extra_kwargs = {'menu':{'required':False}} class CustomerSerializer(serializers.ModelSerializer): class Meta: ordering = ['name'] model = Customer fields = ("id","name","surname","order") class OrderSerializer(serializers.ModelSerializer): orders = ProductSerializer(many=True,read_only=True) restaurant = RestaurantSerializer(read_only=True) customer = CustomerSerializer(read_only=True) class Meta: ordering = ['-id'] model … -
Is There An URL That I Can Use To Implement Authentication With Google OAuth2 With Django? [closed]
I'm working on an online Chess Game with Python and Django, but I've gotten a bit stuck on the authentication. I've tried searching the Internet, even on Stack Overflow, but can't find an answer, but I'm basically looking for a url that I can use in my code to exchange an authorization code for the refresh/access token so I can impliment the Log In with Google button. Could someone help me? I know the question might seem a bit silly and simple, but I can't seem to find an answer. Thanks. -
Django get data of object from ManyToManyField form
Hello i created this form : class CartForm(ModelForm): class Meta: model = Cart fields =( 'products',) from theses models : class Product(models.Model): title = models.CharField("Titre", max_length=120) subtitle = models.CharField("Sous-titre", max_length=250) description = models.TextField("Description") picture = models.ImageField(upload_to='objects/') enabled = models.BooleanField("Activé") class Cart(models.Model): products = models.ManyToManyField(Product) and i want to display on my template an list of choice with their data So i send form from views but i don't find any way to get the products description i only get their names ! please help me have a nice day -
Changing the table DRF Token Authentication uses
I have a React Native application that uses a Django backend. I wanted to handle authentication using tokens. I've followed the example at https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication but the issue is that my login is handled this way: I have an OAUTH at the RN application for google login. I get the email from there and send it to my backend. I'd want to get a token for that email and pass it back to my application Current implementation def generateToken(email): Token.objects.get_or_create(email=email) class Authentication(APIView): def post(self, request): userDeserialized = Users.objects.filter( email=request.data['email']) user = UsersSerializer(userDeserialized, many=True) generateToken(request.data['email']) Now this obviously won't work since DRF TokenAuth is looking at the Django admin User table. I want it to look for the email in my Users table. What's the way I could pull that off? -
Google App Engine Django project read-only file system
I'm deploying my project on Google Cloud. All works fine, but uploading images through admin page is failing It gives [Errno 30] Read-only file system: error. I couldn't see any setting to give the write permission on driver etc. Settings.py STATIC_ROOT = 'static' STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ ........ ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Traceback Environment: Request Method: POST Request URL: .../admin/Blog/post/7/change/ Django Version: 2.2.7 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Blog'] Installed 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'] Traceback: File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in change_view 1637. return self.changeform_view(request, object_id, form_url, extra_context) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in … -
Routing Issue Dash Visualization to Django App
I am trying to add a simple bar chart to my app but while going through a tutorial, I've added in the bottom portion to my Settings.py code and now my app will not load at all. I've tried adjusting this line to just 'routing.application' and moving it to the bottom of my code but neither has worked. Any thoughts? Error: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run application=self.get_application(options), File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 132, in get_application return StaticFilesWrapper(get_default_application()) File "C:\Python38\lib\site-packages\channels\routing.py", line 30, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'django_dash.routing Settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
Django form fields are not displayed
I want to make a form for adding comments, but I only display a form without fields for input, it does not give any errors. I would also like to know how this code can be improved. Any help is appreciated! Here is my forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] views.py: def comments(request, id): if request.method == 'POST': cf = CommentForm(request.POST or None) if cf.is_valid(): body = request.POST.get('body') comment = Comment.objects.create(post=post, user=request.name, body=body) comment.save() return redirect(post.get_absolute_url()) else: cf = CommentForm() context = { 'cf': cf, } return render(request, 'main/article_detail.html', context) urls.py: from django.urls import path, include from . import views from .views import * urlpatterns = [ path('', PostListViews.as_view(), name='articles'), path('article/<int:pk>/', PostDetailViews.as_view(), name='articles-detail'), path('register/', register, name='register'), path('login/', login, name='login'), ] My form in template: <form method="POST"> {% csrf_token %} {{ cf.as_p }} <button type="submit" class="btn btn-primary" style="width: 100px;position: relative;">Submit</button> </form> my models.py: class Comment(models.Model): post = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['date'] def __str__(self): return f'Comment {self.body} by {self.name}' -
Stripe - Creating new card for customers
I'm trying to create a card for customers in these steps: 1. Retrive Customer customer = stripe.Customer.retrieve(user_stripe) 2. Token token = request.POST['stripeToken'] 3. Create a new card card = customer.Cards.create(card=token) I'm having a problem with step-3. Seems like 'Cards' is backdated. I also tried card = customer.sources.create(card=token) from some other StackOverflow similar question. But 'sources' are also backdated I think. Now I'm stuck in the middle of a project. Please help me with this. -
Add extra field to ModelSerializer
I want to make a quiz app and I have two models that looks like this: class Question(models.Model): question = models.CharField(max_length=100) class Answer(models.Model): answer = models.CharField(max_length=30) is_true = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) Now I want to create a ModelSerializer that contains the question and the answes related. Something like this: [ { 'question': 'Something', 'answers': [ 'something1', 'something2', 'something3' ] } ] The problem that I face is that the ForeignKey is in the Answer model not in the Question model. How can I add the Answers in the Question model? Thanks