Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sort list
I have this queryset: <QuerySet [<ProductAttributeValue: Utilizare: Lazurán 3 în 1 Lazur Protector se utilizează pentru lăcuirea decorativă.>, <ProductAttributeValue: Randament: 16 m2/lit., într-un strat>, <ProductAttributeValue: Straturi recomandate: 2>, <ProductAttributeValue: Timp de uscare la 23 °C: 2 ore>, <ProductAttributeValue: Timp de reaplicare la 23 °C: 2 ore>, <ProductAttributeValue: Mod de aplicare: după o amestecare prealabilă se aplică cu pensula>, <ProductAttributeValue: Ambalare: 0.75L, 2.5L>]> I would like to sort this queryset by fields name. For example when I display it I want that order: (Utilizare, Mod de aplicare, Randament, Ambalare, Straturi recomandate, Timp de uscare la 23 °C) There is any solution to sort this list in a given order? -
How to implement a base form in multiple views in Django?
So I have a base.html file where all the components that are common in all the other templates are present. I'm trying to implement Newsletter form functionality in my django project. This form should be displayed on all the pages(in the top navbar). But the problem here is that this form only shows up on base.html and not the other template pages which extend this file. base.html {% load static %} <html lang="en"> <body> <div id="overlay"> <div class="overlay-body form-group"> <h2>Subscribe to our newsletter</h2> <form method="post"> {% csrf_token %} {{form}} <button type="reset" onclick="off()">Cancel</button> <button type="submit" value="submit">Submit</button> </form> </div> </div> <div class="container"> <header> <div> <div class="col-4 "><a id="blog-side" onclick="on()">Subscribe</a></div> <div class="col-4 "> <img src="{% static 'img/logo.png' %}" alt="Logo"> <a href="{% url 'home' %}" class="title">Blog</a> </div> <div class="col-4 "><a href="{% url 'about' %}" id="blog-side">About</a></div> </div> </header> {% block content %} {% endblock content %} </div> </body> </html> Here's the Newsletter form from models.py class Newsletter(models.Model): email = models.EmailField() entered_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def __str__(self): return self.email forms.py class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ('email', ) Any idea as to how to setup this form in the other templates? -
Django search with greek characters
I have tried a lot of backends in my django application, always using unaccent extension. The django documentation mentions that if you search this: Author.objects.filter(name__unaccent__icontains='Helen') You get this: [<Author: Helen Mirren>, <Author: Helena Bonham Carter>, <Author: Hélène Joy>] But how can this work for greek characters also? I have a product with title='σουπερ' and when i search like this Product.objects.filter(title_el__unaccent__icontains='σουπερ') I get this: <ProductQuerySet [<Product: σουπερ>]> But if i search like this: Product.objects.filter(title_el__unaccent__icontains='σούπερ') I get this: <ProductQuerySet []> So maybe unaccent works for english characters only (Spanish in the django documentation is english characters)? And if so how can I extend this functionality for greek characters? -
How to get a queryset given by the product of two other one?
I have the following class in django: class Income(models.Model): product=models.ForeignKey() byproduct=models.ForeignKey() quant_jan=models.DecimalField() quant_feb=models.DecimalField() price_jan=models.DecimalField() price_feb=models.DecimalField() ..... Now in my view I have created the following variable: monthly_income= list(0 for m in range(12)) I want to fill this variable with the product of quant*price for each month (e.g. in monthly_income[0] = quant_jan*price_jan and so on). How could get it with python? -
How to access multiple files from Gallery using HTML?
<input type='file' multiple name='file' /> This allows us to select only one file from Gallery Folder. Any idea how can we select multiple Files from Gallery. -
I am not able to run myserver in django because of this error, I tried installing mysqlclient but i am not able to install that module
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\leads\virtualenv\lib\site-packages\django\db\backends\mysql\base.py", line 16, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\saikr\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\saikr\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\leads\virtualenv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\leads\virtualenv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\leads\virtualenv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\leads\virtualenv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\leads\virtualenv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\leads\virtualenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\leads\virtualenv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\leads\virtualenv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\saikr\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\leads\virtualenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\leads\virtualenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\leads\virtualenv\lib\site-packages\django\db\models\base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\leads\virtualenv\lib\site-packages\django\db\models\base.py", line 325, … -
datetime.now() returns utc-5:00 value when running from program but returns correct system datetime when running from terminal in python
I need to set a value to the system datetime in my code. In settings.py, I have commented TIME_ZONE and USE_TZ= True. And in my file the code looks like: import datetime checkedin_dt = datetime.datetime.now() logger.info(checkedin_dt)-- gives me a value that is utc-5:00 However, when I run the same thing in the terminal, it gives me the correct systemdatetime. I want my code to fetch the systemdatetime without setting any specific timezone in settings.py Any idea why this isn't working in the code. The db is sqlite and the application is a django application. -
Django - POST is_valid() false, no erro and no writing into the db
i have a simple html form, where i can add some data and submit it to be added to the db. this is the form: <!-- PAGE CONTAINER--> <div class="page-container"> <!-- MAIN CONTENT--> <div class="main-content"> <div class="section__content section__content--w1830"> <div class="container-fluid"> {{ forms.errors }} {{ forms.non_field_errors }} <h1>Artikel</h1> <br> <br> <div class="card"> <div class="card-header">Artikel hinzufügen</div> <div class="card-body"> <form action="" method="post"> {% csrf_token %} {{ forms.ArtikelForm }} <div class="form-group"> <div class="row form-group"> <div class="col-4"> <label for="type" class="control-label mb-1">Typ</label> <select name="type" id="type" class="form-control" value="{{ ArtikelForm.artikel_typ }}"> <option value="0">Bitte auswählen</option> <option value="1">Raum</option> <option value="2">Artikel</option> <option value="3">Gerät</option> <option value="4">Marketing</option> <option value="5">Labor</option> </select> </div> <div class="col-8"> <label for="bezeichnung" class="control-label mb-1">Bezeichnung</label> <input id="bezeichnung" name="bezeichnung" type="text" class="form-control" data-val="true" value="{{ ArtikelForm.bezeichnung }}" data-val-required="Bitte tragen Sie eine Bezeichnung ein!" aria-required="true" aria-invalid="false" placeholder="Bitte tragen Sie eine Bezeichnung ein."> </div> </div> </div> <div class="card-body card-block"> <div class="row form-group"> <div class="col-4"> <label for="menge" class="control-label mb-1">Menge</label> <input id="menge" value="{{ ArtikelForm.menge }}" type="number" class="form-control" data-val="ture" data-val-required="Bitte tragen Sie die Menge ein!" aria-required="true" aria-invalid="false" placeholder="Bitte geben Sie die Menge an."> </div> <div class="col-4"> <label for="einheit" class="control-label mb-1">Einheit</label> <select name="einheit" value="{{ ArtikelForm.einheit }}" id="einheit" class="form-control" data-val-required="Bitte tragen Sie die Einheit ein!" aria-required="true" aria-invalid="false"> <option value="0">Bitte auswählen</option> <option value="Euro">Euro</option> <option value="Prozent">Prozent</option> <option value="Minuten">Minuten</option> <option value="Stück">Stück</option> <option value="pauschal">pauschal</option> </select> … -
Recording 24bit WAV in browser
I'm looking for a way to record 24 bit WAV in the browser - I'm building an app with a React front end and Django back end that processes the WAV file and needs it to be 24 bit. Converting on the back end has not produced the exact results I need. I've tried Recorder.js, react-mic and a few other ways of doing this but none seem to offer 24 bit. I've tried adding in 24 bit to something like Recorder.js but get stuck trying to convert float 32 to PCM 24 - I end up with glitchy static. I'm open to other solutions but js is preferred. -
Making a query in django and return sum of all my objects
i have this Model class Invoice(models.Model): field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10) amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10) price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10) i can have several Invoice's, so i want to do like (amount_field2*price_field2) and SUM to all Invoices to have a total in the end. i need to do this in my view because i waint to return the total to my template. -
how to create a table with sum of two different queryset
I have the following model in my django app: class Budget_Vendite(models.Model): product=models.ForeignKey() byproduct=models.ForeignKey() quant_jan=models.DecimalField() quant_feb=models.DecimalField() quant_mar=models.DecimalField() price_jan=models.DecimalField() price_feb=models.DecimalField() price_mar=models.DecimalField() I want to create a dataset that for each byproduct figure out the montly amount given by quant_jan*price_jan Ad example: byproduct | jan | feb | byproduct_1 | quant_jan*price_jan | quant_feb*price_feb | -
Django form validation no function call
I have the following problem. I have the forms.py file: @parsleyfy class FilterWebsitesForm(forms.Form): domain = forms.RegexField(min_length=3, regex=re.compile("^[a-zA-Z0-9-_., ]+$"), error_messages={'invalid': ("Only these characters are acceptable in a domain name: letters, numbers, hyphens, spaces, commas and dots.")}, required=False, label='', widget=forms.TextInput(attrs={'placeholder': 'domain', 'class': 'text_search padding_both', 'id': 'domain_id'})) views.py: from myapp.forms import FilterWebsitesForm def websites_display(request): limit = 100 fwfForm = FilterWebsitesForm() start = time.clock() if request.method == 'POST': fwfForm = FilterWebsitesForm(request.POST or None) if fwfForm.is_valid(): queries = {} ... main_display.html <title>{{ title }}</title> <script type="text/javascript"> $(document).ready(function(){ $('#button_search').click(function() { $('#first').show(); $('#records_list').block({ message: null }); }); }); </script> In the main_display.html file, the loader is displayed until the result is returned. When a user enters the correct characters, the loader works fine. Disappears when the result is returned. When a user enters the wrong characters into the form, the Regexfield displays the message, but also runs the javascript function, and that is not what I want because the loader runs forever. The problem is when the validation error message is displayed, the websites_display function is not executed (breakpoint at limit = 100), that's why I can't check {% if form.errors %} to run the javascript function. I can't find any information about this problem. Thank you. -
Custom Sorting in Django Models
I have a version column declared by type TEXT +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ | 2019.10.0 | 200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ While retrieving from database, I use Projects.objects.all().order_by('version') after which the data is fetched in following order +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.10.0 |200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ Expected Output +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ | 2019.10.0 | 200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ The function in my .py file def getUpdateData resultSet = Projects.objects.all().filter(version_name__gte='2019.1.0').extra( select={'num_from_name': 'CAST(version_name AS FLOAT)'} ).order_by('num_from_name') valueList = list(resultSet) return valueList Any help is widely appreciated, Thanks in Advance. -
Working with multiple instances in a formset
A am trying to make a table, where each row represents an instance of a model. class Dt(UpdateView): model = Downtime form_class = DowntimeForm def get(self, request, *args, **kwargs): # Get a foreignkey object from request kwarg order_id = self.kwargs['pk'] order = Order.objects.get(id=order_id) # Create a qs from that kwarg dt_list = Downtime.objects.filter(order=order) # Create a formset based on the qs length DtFormSet = formset_factory(self.form_class, extra=len(dt_list)) formset = DtFormSet() # Populate the formset with data before rendering i = 0 for dt_session in dt_list: formset[i].initial = { 'dttype': dt_session.dttype, 'start': dt_session.start, 'end': dt_session.end, } print(formset[i]) i += 1 context = { 'formset': formset, 'order_id': order_id, } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): formset = self.get.formset(self.request.POST) if formset.is_valid(): pass I've done something like this before, but i didn't have to pop a kwarg from request, so i defined the formset inside a class-view and iniated it inside get() method. But now it doesn't work (returns empty formset). So my questions is: is there a better approach to this? I'm new to django and might not be using best tools available. Maybe UpdateView isn't appropriate here, for example. -
Unable to resize image before uploading to Google Storage
I have the following code with reference to https://github.com/jschneier/django-storages/issues/661, but it doesnt work, the default unsized image is being stored. models.py class Product(models.Model): name=models.CharField(max_length=100) image=models.ImageField(default='default.jpg',upload_to='productimages') price=models.FloatField() def generate_thumbnail(self,src): image = Image.open(src) # in memory image.thumbnail((400,300), Image.ANTIALIAS) buffer = BytesIO() image.save(buffer, 'JPEG') file_name = os.path.join(settings.MEDIA_ROOT, self.image.name) temp_file = InMemoryUploadedFile(buffer, None, file_name, 'image/jpeg', len(buffer.getbuffer()), None) return temp_file def save(self, *args, **kwargs): self.image=self.generate_thumbnail(self.image) print(self.image.width) #prints the original size print(self.image.height) super(Product,self).save(*args, **kwargs) -
Fetch MongoDB data's into python
I am creating a pie chart in web using python and django. Here's my code: views.py: from django.shortcuts import render import pymongo from pymongo import MongoClient def dashboard(request): mongo_client = pymongo.MongoClient("mongodb://localhost:27017/") db = mongo_client["trackandtrace_TN_PROD"] db_collection = db["defectdashboard"] document = db_collection.find() for item in document: def_cod = (item['defect_code']) print(def_cod) return render(request, 'defectdashboard/def_dash.html') def_dash.html: function defectCode() { var data = new google.visualization.DataTable(); data.addColumn('string', 'defect code'); data.addColumn('number', 'affected'); data.addRows([ ['defect code 1', 518], ['defect code 2', 400], ['defect code 3', 188], ['defect code 4', 118], ]); var options = {title:'Top 4 Defect Code', width:500, height:500}; var chart = new google.visualization.PieChart(document.getElementById('code_div')); chart.draw(data, options); } As you can see in html file. i am populating the data's as static. Now i want to display my MongoDB values in chart . How to fetch and display? -
Can I upload my python binaries in ecrypted form and be able to be executed by Django?
I know that what I am asking might be stupid, but I have to ask since my research returned very limited results. I want to deploy my django/python/postgresql (v2/v3.7/v11) project to the customer's server (ubuntu 18.04). However I have been asked by my boss if there is any way to encrypt the python binaries (*.pyc files) so as they are not reverse-engineered back to the source code. Or is there any workaround for not allowing others to view python code and at the same time this code can be executed? I am all pro open source coding, but this is not my decision, so be gentle (of course all 3rd party libraries won't be encrypted. Just our code). -
Django photologue images and queryset
I've added photologue to my project, because it does 99% of the things I was trying to achieve by myself. Now I need to connect the uploaded images and images in galleries to my posts. This is why I've added a ManyToMany field to the photologue Photo model Class ImageModel(models.Model): post_images = models.ManyToManyField(Post, blank=True) And will do the same to the Gallery model class Gallery(models.Model): post_gallery = models.ManyToManyField(Post, blank=True) Now my idea is to be able to add a gallery and/or specific images to my post . Both options should be available. The queryset I would like to have is to get all the individual images, that are attached to the post and also all the images in the gallery if a gallery is attached. Then to pass and render them to the page in some sort of gallery (Slider, carousel or something else). I'd like to be able to get them in the template with one for loop, so I think the queryset have to be one. I have a view that renders the specific page type and I don't know if I should include the queryset and context in this function or to create a new one for … -
How to set maximum connection age for Amazon RDS Instance, PostgreSQL, Django/Python Web Application?
I have been searching for a way to set a maximum connection age for all connections to my Amazon RDS PostgreSQL instance. Currently, when querying the database to add data after a user has registered in my Django application, the connection created with the database seems to never cease. I was able to tell as the cost of running the database grew dramatically with incredibly minimal use. My main question is, how am I able to prevent this connection never ceasing, and is there a way I can see the current connections to the Amazon RDS instance? -
How to fix no of child to parent in django-mptt?
I'm want to fix 2 children for each parent. Models.py class CoachingRegistration(MPTTModel): uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4) placement_id = models.CharField(max_length=13) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['placement_id'] def __str__(self): return str(self.placement_id) Please help me how to fix this. -
Django custom three-step registration flow without using third-party library
I have a Django application I have implemented a two-step registration flow for but the flow has recently been changed. The new flow requires that when a user registers, a verification email is sent but he/she shouldn't be able to login until the admin approves it followed by a notification email. How can I achieve this without using libraries/apps such as Django-registration-redux and Django-allauth? Please, include working snippets. -
Error from Tasks job when referencing a model that uses from django.contrib.auth.models import User
My blog.models is using: from django.contrib.auth.models import User That model is being called from my script which I run as a task every hour. Here's the error that I'm seeing: Traceback (most recent call last): File "/home/redinv/src/cron.py", line 8, in <module> from blog.models import ImagePost, MyPost, ScheduledPost File "/home/redinv/src/blog/models.py", line 3, in <module> from django.contrib.auth.models import User File "/usr/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/usr/lib/python3.8/site-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 60, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 2020-06-25 00:50:25 -- Completed task, took 3.95 seconds, return code was 1. In my settings file under INSTALLED_APPS =, I already have: 'django.contrib.auth', This code is of course working locally on my machine and I'm trying to figure what's the issue here? I tried running that script from two locations to see if there was an issue trying to find the import files: … -
Convert sql server queries to django model queries
"UPDATE Inventory_ballance_tbl SET Item_amount_per_Gm_Ml = Inventory_ballance_tbl.Item_amount_per_Gm_Ml - Menu_portion_tbl.Item_size * Sale_history_tbl.Quantity FROM Inventory_ballance_tbl INNER JOIN Menu_portion_tbl ON Inventory_ballance_tbl.Item_name = Menu_portion_tbl.Item_name CROSS JOIN Sale_history_tbl" -
django-channels asgi deploy problems
On localhost(on my pc) everything works fine, no errors, but when I deploy it on ubuntu server, django-channels stop working correctly, the problem is ModuleNotFoundError: No module named 'asgiref.local' when I run daphne -p 8001 <myproject>.asgi:application, but I have installed asgiref CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } asgiref==3.2.7 daphne==2.5.0 Django==3.0.6 channels==2.4.0 channels-redis==2.4.2 Error log: Traceback (most recent call last): File "/usr/bin/daphne", line 11, in <module> load_entry_point('daphne==1.4.2', 'console_scripts', 'daphne')() File "/usr/lib/python3/dist-packages/daphne/cli.py", line 144, in entrypoint cls().run(sys.argv[1:]) File "/usr/lib/python3/dist-packages/daphne/cli.py", line 174, in run channel_layer = importlib.import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./Career/asgi.py", line 8, in <module> from channels.routing import get_default_application File "/home/luka/.local/lib/python3.6/site-packages/channels/routing.py", line 7, in <module> from django.urls.exceptions import Resolver404 File "/home/luka/.local/lib/python3.6/site-packages/django/urls/__init__.py", line 1, in <module> from .base import ( File "/home/luka/.local/lib/python3.6/site-packages/django/urls/base.py", line 3, in <module> from asgiref.local import Local ModuleNotFoundError: No module named 'asgiref.local' and when I run pip install -r requirements.txt get message … -
how to use two instance id of foreign key
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) Shop_category = models.CharField(max_length=200, null=True, ) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) description = models.TextField(null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card. On the product card, there is an order button that adds the product in order after submitting the selected product will print with the remaining filled of order that shown in the image how I create order form show that I get the id of shop and product