Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template not displaying React component
I have installed all the packages I need, And I believe my webpack is setup correctly. I can run the server and the dev script with no errors at all. If I was to put anything in the HTML(e.g. text) file, it shows. But no react components on it. Webpack.config const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("development"), }, }), ], }; HTML <body> {% load static %} <div id="main"> <div id="app"> </div> </div> <script src="{% static 'frontend/main.js' %}"></script> </body> React import React, { Component } from "react"; import ReactDOM from 'react-dom'; export default class App extends Component(){ constructor(props){ super(props); } render(){ return <h1> Site Placeholder </h1> } } ReactDOM.render(<App />, document.getElementById('app')); The index.js just has an import: import App from "./components/App"; Views simply renders the index.html def index(request, *args, **kwargs): return render(request, 'frontend/index.html') I am not getting any errors anywhere, but my html is blank. In chrome inspect, I can see that there is the main.js … -
Django and HTML Dropdown : Populate Parent / Child field with Selected any one of the Child Attributes
I have 3 models which are being used for Dropdown, and user can select value from any of dropdown. When user select the parent the child dropdown auto-filters (this is working), however need a functionality where, when a user select a child, parent dropdown will also get filter. While doing research I came across with such functionality on site "https://www.hertzcarsales.com/nashville.htm?utm_source=google&utm_medium=organic&utm_campaign=GoogleLocalListing". Due to security reason cannot share actual models. however can refer to the site. User can select Vehicle Make, and the model + Body Style will auto filter, and when user selects just Body Style, then Make & Model will be filtered accordingly. For example, in below screenshot I just selected Body Style as Truck, and all Make & Model are auto-filtered. Please suggest or point me how this can be doable, just a pointer or small suggestion would help. I did tried using JavaScript, but unable to do reverse dropdown filter. -
Validate user name in django by jquery and javascript
Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username function delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, ms || 0); }; } $('#id_username').on('focus', function(){ if ( $(this).val() == '' ){ $(this).attr('oldValue',''); } else { $(this).attr('oldValue',$(this).val()); } }); $('#id_username').keyup(delay(function () { var currValue = $(this).val(); var oldValue = $(this).attr('oldValue'); if (currValue == oldValue){ // Not sending ... } else{ // create an AJAX call $.ajax({ data: … -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Bad Gateway - error 504
I am getting this error from my django application running on ubuntu version 20.04. I have tried all the solution I have seen online, including here on StackOverflow but none of them seems to have solved problem. Here is the error: [2021-09-27 21:32:14 +0000] [607] [INFO] Worker exiting (pid: 607) Sep 27 21:32:14 server.varsell.com gunicorn[608]: [2021-09-27 21:32:14 +0000] [608] [ERROR] Exception in worker process Sep 27 21:32:14 server.varsell.com gunicorn[608]: Traceback (most recent call last): Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Sep 27 21:32:14 server.varsell.com gunicorn[608]: worker.init_process() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_proce> Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.load_wsgi() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.wsgi = self.app.wsgi() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.callable = self.load() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Sep 27 21:32:14 server.varsell.com gunicorn[608]: return self.load_wsgiapp() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Sep 27 21:32:14 server.varsell.com gunicorn[608]: return util.import_app(self.app_uri) Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app Sep 27 21:32:14 server.varsell.com gunicorn[608]: mod = … -
How to convert post to Json - Django
I'm trying to convert data from a post to Json formed. But I still haven't had success. I tried to do in this format Unfortunately I couldn't think of anything. Could anyone help? if post: import re pattDet = re.compile('^([a-zA-Z_]\w+.)\[([0-9_\-][\w\-]*)\]\[([a-zA-Z_\-][\w\-]*)\]$') pattProd = re.compile('^([a-zA-Z_]\w+.)\[([0-9_\-][\w\-]*)\]\[([0-9_\-][\w\-]*)\]\[([a-zA-Z_\-][\w\-]*)\]$') pprint.pprint(post) det = [] prodtem = [] count = 0 for post_name, value in post.items(): try: det_count = int(pattDet.match(post_name).group(2)) if pattDet.match(post_name).group(1) == 'det': det[pattDet.match(post_name).group(3)] = value except: pass try: if pattProd.match(post_name).group(1) == 'prod': if count == int(pattProd.match(post_name).group(3)): prodtem.insert(count, {pattProd.match(post_name).group(4): value}) else: count += 1 except Exception as e: print(e) pass result.append({ 'det': det, 'prod': prodtem }) -
How to use a request.session stored value within a DetailView as the initial data to a ModelForm input field?
I'm a beginner at Django and I'm currently developing my first project. I'm using DetailView to display information from an object and in this same template there's a button that redirects to a ModelForm template. I've already gotten how to prepopulate the user field with form.save(commit=False) and a date field by simply setting a default on models. But I'm having trouble setting a ForeignKey field up. I've already tried different methods and variations of them but none worked. The one below is the last one I've tried. I've already studied and tried to make it work but I'm not sure how to use django sessions to pass the '''Book.id''' or anything that could possibly replace it from the DetailView to the ModelForm field. There were times I've gotten an error saying certain object was not JSON serializable then I've tried to make it work importing serializing modules and it didn't work as well. I also have doubts if I'm using the best method to achieve what I want using the DetailView class. Obs.: the input field is there with the options to pick. My intention is to set the initial value with previous page object. views.py class BookView(DetailView): model = … -
Django model where u can specify either a specific date, year, year range or unknown
the idea is that the field could take the following inputs 1926; 01/04/1997; 1937-1940,unknown is this even possible? how about django admin would it be possible to integrate? -
RuntimeError: Model class apps.concert.models.Band doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am attempting to import models from my concert app into an uploader app. However, when I do so, I get this error. RuntimeError: Model class apps.concert.models.Band doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have tried a number of solutions listed on StackOverflow but none of them work. I'll include my file setups here and would love help finding a solution. I'm banging my head against the wall trying to figure this out since I've not had this issue in the past. settings.base INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', 'storages', 'user', 'concert', 'uploader', ] apps.concert.models from django.db import models from django.db.models import ( CharField, TextField, ForeignKey, BooleanField, DateField, FileField, IntegerField, CASCADE ) import uuid import pdb def user_directory_path(instance, filename): random_file_name = "".join([str(uuid.uuid4().hex[:6]), filename]) return "concerts/{0}/{1}/{2}/{3}/{4}/{5}".format(instance.concert.date.year, instance.concert.date.month, instance.concert.date.day, instance.concert.venue, instance.concert.pk, random_file_name) class Band(models.Model): name = TextField() def __str__(self): return self.name class Concert(models.Model): venue = TextField() date = DateField() city = CharField(null=True, blank=True, max_length=100) state = CharField(null=True, blank=True, max_length=100) country = TextField() band = ForeignKey(Band, on_delete=CASCADE, related_name='concert') # user = ForeignKey(User, on_delete==CASCADE, related_name='user') def __str__(self): return self.venue class Song(models.Model): title = TextField() concert = ForeignKey(Concert, on_delete=CASCADE, related_name='song') # user = … -
How to do multiple pages with Django
I got some flash cards My flash cards I want to increase them, but they should not all append on one page, I want to have a page layout below. Like this: Like this: How should I do? -
How to setup django-sslserver with openssl?
I have installed OpenSSL64 successfully on my windows machine. I have a django project that I want to use SSL on. I've found github repo called "django-sslserver". I've set it up. The issue I am having is, when launching the django project through this command ($ python manage.py runsslserver myipaddress:portnumber), the https doesn't work and the browser shows that a certificate while it does exist, it is however not secure and its given by "localhost". So I figured I just need to get the proper certificate. My question is, how do I create the proper crt and key through openssl? I need to execute this command ; $ python manage.py runsslserver --certificate /path/to/certificate.crt --key /path/to/key.key -
Django filter object by ManyToMany and only return those ManyToMany relationships that match
class Category(models.Model): .... class User(models.Model): ..... category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) group = models.ManyToManyField( Group, through="UserGroup") class Group(models.Model: .... class UserGroup(models.Model): ...... user = models.ForeignKey( User, on_delete=models.CASCADE) Group = models.ForeignKey( Group, on_delete=models.CASCADE) ..... I want to be able to return the Groups that contains a User with a certain category which I can do with... queryset = Group.objects.all() category = Category.objects.get(pk=category_id) queryset = queryset.filter(user__category_id=category_id) But this still returns all the Users associated to that Group even if the User.category does not equal the given category_id. How do I filter those many to many relationships also to return the Group where Users have that category and ONLY those Users within the Group? -
Hi i am getting user is AnonymousUser even i am passing valid token
hi i am using djangorestframework-simplejwt==4.4.0 and creating token using it but django give me AnonymousUser when i am trying to pass this token in side Authorization Bearer my restframework setting is : 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } from datetime import timedelta ... SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=50), 'REFRESH_TOKEN_LIFETIME': timedelta(days=60), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } view code is given below where i am trying to use it class PostProductsReviewsView(CreateAPIView): # permission_classes=[IsAuthenticated] serializer_class = ReviewsSerializer def get(self,request): print(request.user) user_id=request.user.id try: user=User.objects.get(id=user_id) except: return Response({"error":"user is not authenticated"},status=status.HTTP_401_UNAUTHORIZED) data=request.data stars=data.get('stars') title=data.get('title') review_content=data.get('review_content') review_content=data.get('product') quesry_data={ 'stars':stars, 'title':title, 'review_content':review_content, 'user':user, 'is_active':True } # data['user']=user serializer=ReviewsSerializer(data=quesry_data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) please help me when i copy and test on jwt.io this token contain all details but show invalid signature please help me -
Django Paginator not working after first page
I am doing a search that returns different model information. I want to have pagination on the results, and I have tried to do it with my get_context function (to figure out search parameters) and then a Paginator call. It returns the first page, but the next links in the template do not work. I get an error: UnboundLocalError at /search/ local variable 'my_object_list' referenced before assignment. My Search_Results_View looks like this: class SearchResultsView(LoginRequiredMixin,ListView): model = Program template_name = 'search_results.html' def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) # all_program_results = None segment_results = None segment_program_results = None segment_program_list = None segment_ids = None q_words = [] query = self.request.GET.get('q') start_date = self.request.GET.get('start_date') end_date = self.request.GET.get('end_date') svc_choices = self.request.GET.getlist('service_choices') print("Query = %s" % query) print("Start Date = %s " % start_date) print("End Date = %s " % end_date) print("SVC_CHOICES = %s" % svc_choices) for choices in svc_choices: print("Service choices = %s " % choices) if start_date and end_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__range=[start_date,end_date]).order_by('id') else: if start_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__gte=start_date).order_by('id') else: if end_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__lte=end_date).order_by('id') else: all_program_results = Program.objects.filter(service__in=svc_choices).order_by('id') # We have gotten every program that applies if not query: print(" ALL programresults_count = %s" % all_program_results.count()) else: if re.match('^[0-9]+$',query): #user entered Program … -
Django + Vue deployment pythonanywhere.com
I am new to vue and cannot figure out how to get my Django/Vue app deployed on pythonanywhere.com. For the backend I am using cookiecutter which I have deployed as normal using [this guide][1] . This is working and I can view the API endpoints. I have been having difficulty connecting up the vue part, this is probably due to being new to JS frameworks so I am not entirely sure how they run in production. From [this post][2] I know I need to serve my Vue files as static files but I dont know how to do this. I have tried to build my vue project on my local machine which creates a dist folder, I added the contents of this folder to my django static folder and ran collectstatic command but this has not worked for me. Does anyone have experience with Vue and Django on pythonanywhere that could point me in the right direction? Any ideas of how to get this working? Thanks, John -
(Bad Gateway) ERROR 502 Nginx, Gunicorn, Django DRF, Vue.js
I have deployed ecommerce made with Django and Vue.js on a VPS. Everything is working fine, but when I try to use POST method, Error 502 appears in console and nothing happens. The API is able to show products from Django Admin, but I can't post anything from the frontend. It always gives me this Error 502 problem. I have been trying to solve this for a few day already and still don't get what is wrong. Hope you can help. Thank you! upstream perulab_app_server { server unix:/webapps/perulab/venv/run/gunicorn.sock fail_timeout=0; } server { listen 8000; listen [::]:8000; server_name 172.16.7.52; client_max_body_size 40M; location / { root /webapps/perulab/web-frontend/dist; try_files $uri /index.html; index index.html index.htm; } location /static/ { root /webapps/perulab/web-backend; } location /media/ { root /webapps/perulab/web-backend; } location /api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://perulab_app_server/api/; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; } location /admin/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://perulab_app_server/admin/; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; } } When I try to run gunicorn --bind 172.16.7.52:8000 core.wsgi this is what appears: [2021-09-27 14:55:59 -0500] [230558] [INFO] Starting gunicorn 20.1.0 [2021-09-27 14:55:59 -0500] [230558] [ERROR] Connection in use: ('172.16.7.52', 8000) … -
Is it good practice to use HTML forms to display data?
I am planning on using the form-control classes from Bootstrap to display data. I have an inclusion template tag that generates a "form" from objects in the DB. Is this a good practice? Or should I be investing my time in searching for a better way to display data? -
Deploying Django app with PointField, gis_model and postgris database
I'm trying to deploy my first wab app, and I need to use Postgris databas and tacking geolocation for some models. I found it very hard to set this deployement, I get some errors and can't figure out how to solve the error, my question is there is a tutorial that I can see to learn how to deploy sache application, all tutorial I found don't see haw to set up heroku for such case. -
Django view triggered twice after submit button
I found out that I returned the context to my HTML template the view called in the first time, after I hit the submit button the view triggered again from the beginning. how I can prevent the view to triggered from the beginning and execute directly the code after is request.method == 'POST'. this is the code of my view def recipe_recommendations(request): print('enter----------------') # add rating of current user to rating matrix person = request.session['person_id'] user_category = FoodCategory.objects.filter( person_id=request.session['person_id']).values_list('category', flat=True) user_category = user_category[0] target_user = add_to_csv(person, category=user_category) # get recommendation recom_size = 5 htop_n_for_target_user = [] unhtop_n_for_target_user = [] htop_n_for_target_user,unhtop_n_for_target_user = get_top_n_for_user(person,recom_size, user_category) # get recipe info and send them to tmeplate id_h_recipes = [] # for i in htop_n_for_target_user: # id_h_recipes.append(i[0]) [id_h_recipes.append(i[0]) for i in htop_n_for_target_user] id_unh_recipes = [] [id_unh_recipes.append(i[0]) for i in unhtop_n_for_target_user] # for i in unhtop_n_for_target_user: # id_unh_recipes.append(i[0]) print(f'-------healthy_ids: {id_h_recipes}') print(f'--------unhealthy_ids: {id_unh_recipes}') # extract 5 healthy recipes h_0_recipe = HealthyRecipe.objects.get(id=id_h_recipes[0]) h_1_recipe = HealthyRecipe.objects.get(id=id_h_recipes[1]) h_2_recipe = HealthyRecipe.objects.get(id=id_h_recipes[2]) h_3_recipe = HealthyRecipe.objects.get(id=id_h_recipes[3]) h_4_recipe = HealthyRecipe.objects.get(id=id_h_recipes[4]) # extract 5 unhealthy recipes unh_0_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[0]) unh_1_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[1]) unh_2_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[2]) unh_3_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[3]) unh_4_recipe = UnhealthyRecipe.objects.get(id=id_unh_recipes[4]) # selected recipe model selected_recipe = SelectedRecipe() if request.method == "POST": # if the … -
Python geojson get centroids of polygon
I have a django model from django-leaflet example project like: from djgeojson.fields import PolygonField from django.db import models class MushroomSpot(models.Model): title = models.CharField(max_length=256) description = models.TextField() geom = PolygonField() After saving a data I get result like: 'title': 'Location 2', 'description': 'This is location 2', 'geom': {'type': 'Polygon', 'coordinates': [[[5.328369, 45.251688], [5.910645, 44.980342], [6.328125, 45.375302], [6.075439, 45.859412], [5.471191, 45.698507], [5.328369, 45.251688]]]} Here how can I get cetroid and area of the polygon ? I tried searching but found very complicated. Any help will be appriciated -
Uploading image/images on Django REST Framework
I am trying to upload images on an endpoint in postman but i'm getting the error in the screenshot below Below is my code for sake of brevity i'll only send the affected parts. Models: class Post(models.Model): content = models.TextField() image = models.ManyToManyField(PostImage,blank=True,related_name='posts_images') class PostImage(models.Model): image = models.ImageField(upload_to='post-images',validators=[FileExtensionValidator(['png','jpg','gif','jpeg'])]) Serializers: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image') class PostSerializer(serializers.ModelSerializer): image = PostImageSerializer(many=True, required=False) class Meta: model = Post fields = ['content','image',] def create(self, validated_data): r_data = self.context['request'].FILES instance = super().create(validated_data) if "image" in validated_data.keys(): images = validated_data.pop('image') else: pass post = Post.objects.create(**validated_data) instance.image.add(r_data) return post Viewsets : class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() -
Render response in django python
Using django framework and rest api framework. os.environ['NO_PROXY'] = '#mylocalhosthere' def api_view(request): #url = '#mylocalhosthere/pcp/customer/' url = '#mylocalhostherepcp/customer/?format=json' r = requests.get(url) data = json.loads(r.text) return render(request,'PcPeripherals/api.html',{'response':data}) This is what my django template looks like: {% block content %} <div class="row"> <div class="column-d-9 column-t-12 column-m-12"> <div id="box_contact"> <div id="box_formas"> <h1>List of customers</h1> {% for i in data%} <strong>{{i.id}}</strong> {% endfor %} </div> </div> </div> </div> {% endblock content %} Any ideas what I am doing wrong? I checked some other variants still no data in my template. -
why does Django not allow users to login?
I'm struggling with login in both the "normal" part of the site and in the standard admin page. I tried to delete the old db and create a brand new one with a new superuser, but I didn't solve the problem. I can submut the form and the server response is 302 and it redirects again in the login page. Can someone help me out? I'm going crazy. All other solution here does not work and even from other sites. I'm on Django 3.1.6 Thanks a lot -
Django Custom User Manager is not called in admin panel
I am implementing a custom user model using AbstractBaseUser and BaseUserManaer . class UserManager(BaseUserManager): def create_user(self,username,password=None): class User(AbstractBaseUser): ... objects = UserManager() When I am creating new users from the the terminal, it is working as intended and the users are getting registered using the custom UserManager. But when using the admin site, the user seems to be using some other user manager, where it should be using the custom user manager. users/admin.py User = get_user_model() class UserAdmin(BaseUserAdmin): ... admin.site.register(User, UserAdmin) -
Get next/previous sibling in Django CMS
I want to make previous/next buttons, which takes user to previous/next sibling, from the template inside Django CMS. I've tried this solution, but it doesn't work. How can I do that? -
Can't I add a list to my models.py in django?
I'm quite new in Django and in this project I need to manage information about a restaurant. The problem is that I can't add more than one ingredient required to a recipe My models.py is this: from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=35) quantity = models.IntegerField() unit = models.CharField(max_length=5) unit_price = models.FloatField() def __str__(self): return self.name class MenuItem(models.Model): title = models.CharField(max_length=35) price = models.FloatField() example = models.ImageField() def __str__(self): return self.title class RecipeRequirement(models.Model): menu_items = models.ForeignKey(MenuItem, default = 1, on_delete=models.SET_DEFAULT) ingredient = models.CharField(max_length=35) quantity = models.FloatField() def __str__(self): return str(self.menu_items) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, default=1, on_delete=models.SET_DEFAULT) timestamp = models.DateTimeField() def __str__(self): return 'Purchase ' + str(self.menu_item) + str(self.timestamp)