Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show Model members in django admin
I need to show all users in the Model (ManyToMany relationship) like this PS: this is from Group Admin as in this Question Show group members in Django Admin but it only works for Group Model. I need it for a custom Model. -
What would be a correct route for the particular view in urls.py?(Django)
I have two classes in model. class Ebuy_Fields(models.Model): source = models.CharField(max_length=10) category = models.CharField(max_length=32) rfq_id = models.CharField(max_length=32) rfq_title = models.TextField() class Ebuy_Detail_Fields(models.Model): rfq_id_final = models.CharField(max_length=10) rfq_id_title_final = models.TextField() These are two different tables but rfq_id_final are common between them. (But they are not related by foreign key) In views.py, def ebuy_detail(request,rfq_id_final): unique_bid = get_object_or_404(Ebuy_Fields,rfq_id_final=rfq_id_final) context = {'i':unique_bid} return render(request,'rfq-display.html',context) This displays the particular view of the particular rfq_id. In urls.py, I tried with this: url(r'^(?P<rfq_id_final>[\w-]+)/$', ebuy_detail, name='ebuy_detail'), In templates when I click this line from the page of another view, <td data-label="RFQ Id"><a href = "{% url 'ebuy_detail'/{{ i.rfq_id }} }">{{ i.rfq_id }}</td> What is the correct way that if the rfq_id and rfq_final_id is same then, it will open the detail view? -
Set AWS S3 ACL per object with Django Storages
I am using django storages with the AWS_DEFAULT_ACL set to public read. However I want to be able to manually save files with default_storage.save() with private ACL. Is there a way to do this with default_storage? Something like: default_storage.save(file_name, ContentFile(content), acl='private') -
How to pass a particular value inside a Tuple that also a tuple in Python in Django?
I have this dictionary for Categories that's a tuple within a tuple however I want to isolate only the literals --> the category names from django.db import models CATEGORIES = ( ('a', 'Clothing'), ('b', 'Electronics'), ('c', 'Furniture'), ('d', 'Kitchen'), ('e', 'Miscellaneous'), ('f', 'None'), ) but in a different file that's views.py is this def show_category_listings(request, category): listings = Listing.objects.filter(category__in = category[0]) cat = dict(CATEGORIES) return render(request, 'auctions/categSpecific.html', { "listings": listings, "category": cat[category] }) and finally in the html is this <li>Category: {{ listing.category }}</li> but what i see is only letters instead of the names look in html is there a way to get only the category names? i couldn't figure out the passing of values in the views.py part. -
How to add search functionality to "list_filter"s input bar?
How to make list_filter's input text area search bar? for example as below if I write to joined_date field "10 august" and hit enter, it should filter and show all the users for corresponding date as below shown enter image description here below i attached snippet from admin.py @admin.register(User) class UserAdmin(BaseUserAdmin): template = "users_admin_template.html" list_display = [ 'first_name', 'last_name', 'surname', 'email', ] list_filter = ['first_name', 'last_name', 'surname', 'email', 'birthday','date_joined', 'country', 'city'] -
Database structure django
I have a MySQL database with three tables (three endpoints in api) but when I added JWT Django authorization it created a few more tables like customuser, tokens. Should I include those tables in my database structure diagrams? -
I want to calculate the GPA and Grade of each students regarding the each subjects. And finally calculate the Total GPA and Grade
i have tired making the models of each subject with gpa and grade. And started calculating GPA and Grade. There are 10 classes with different subjects. Can anyone suggest me the best way of calculating this. class NurseryResult(models.Model): roll_number = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50, blank=False) academic_Year = models.CharField(default=0, blank=True, max_length=50) nepali = models.PositiveIntegerField(default=0, blank=True) nepali_gpa = models.FloatField(default=0, blank=True) nepali_grade = models.CharField(default=0, blank=True, max_length=50) english = models.PositiveIntegerField(default=0, blank=True) english_gpa = models.FloatField(default=0, blank=True) english_grade = models.CharField(max_length=50, blank=True, default=0) math = models.PositiveIntegerField(default=0, blank=True) math_grade = models.FloatField(default=0,blank=True) math_gpa = models.CharField(max_length=50, default=0, blank=True) science = models.PositiveIntegerField(default=0, blank=True) science_grade = models.FloatField(default=0, blank=True) science_gpa = models.CharField(max_length=10, blank=True, default=0) oral_nepali = models.PositiveIntegerField(default=0, blank=True) oral_math_grade = models.FloatField(default=0, blank=True) oral_math_gpa = models.CharField(max_length=50, default=0, blank=True) oral_math = models.PositiveIntegerField(default=0, blank=True) oral_math_grade = models.FloatField(default=0, blank=True) oral_math_gpa = models.CharField(max_length=50, default=0, blank=True) oral_english = models.PositiveIntegerField(default=0, blank=True) hygiene = models.PositiveIntegerField(default=0, blank=True) hygine_grade = models.FloatField(default=0, blank=True) hygine_gpa = models.CharField(max_length=50, default=0, blank=True) grade = models.CharField(max_length=10, default=0) GPA = models.FloatField(default=0) def save_nepali(self, *args, **kwargs): if self.nepali >=90: self.nepali_gpa = 4.0 self.nepali_grade = "A+" elif self.nepali >=80 : self.nepali_grade = "A" self.nepali_gpa= 3.6 elif self.nepali >= 70: self.nepali_grade = "B+" self.nepali_gpa = 3.2 elif self.nepali >= 60: self.nepali_grade = "B" self.nepali_gpa = 2.8 elif self.nepali >= 50: self.nepai_grade = "C+" … -
Converting datetime format got this issue 'str' object has no attribute 'strftime' in DRF
I have a date time value November 10, 2021 which is to be converted into Django default datetime. I tried but got this error. I have a date value which I got from list of dictionaries like this which is a datetime field. created_at = data[0]['created_at'] print(created_at) The print I got is like June 12, 2021 Now I tried this. c = created_at.strftime(('%Y-%m-%d %H:%M:%S')) print(created_at) print(c) When I print c, I got the above error. -
I want to populate / store data from csv into django admin
I want to get data from CSV and populate it to Django admin. but due to foreign key user I am not getting the desired result. def handle(request): df = pd.read_excel('testdata.xlsx') obj=Account.objects.filter(email=df.user[0]) for session_date,session_time,session_name,duration,i in zip(df.session_date,df.session_time,df.session_name,df.duration,obj): models = GuidedSession(session_date=session_date,session_time=session_time,session_name=session_name,duration=duration,user=i) # print(i) print(models # models.save() return HttpResponse(status=200) (Views.py) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60) username = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email class GuidedSession(models.Model): session_date = models.CharField(max_length=200) session_time = models.CharField(max_length=200) session_name = models.CharField(max_length=200) duration = models.IntegerField(default=20) user = models.ForeignKey(Account, on_delete=models.CASCADE) def __str__(self): s = str(self.session_name) return s (Models.py) Let me know the best way to do that. -
ArragAgg annotation wierdness. Is this a bug or a feature?
Quick problem statement. Adding an ArrayAgg (Postgres extensions) annotation is multiplying the values of other annotations, but not always. Details. Given these models: class MemDesc( models.Model): class Meta: verbose_name = "Item Description" ... lots of data fields (Char and Integer fields) class MemStockLineManager( models.Manager): def get_queryset(self): # always fetch related descriptions! return super().get_queryset().select_related('desc', 'allocated_to') class MemStockLine( models.Model): class Meta: verbose_name="Stock Line" # managers. first is default objects=MemStockLineManager() desc = models.ForeignKey( MemDesc, models.PROTECT, related_name='stock') ... data fields ... class ProductCode( models.Model): class Meta: unique_together=[('code','customer'), ('customer', 'description')] customer = models.ForeignKey( 'customers.Customer', models.CASCADE, null=True, blank=True, ) description = models.ForeignKey( MemDesc, models.CASCADE, ) code = models.CharField( max_length = 20) I don't expect MemStockLineManager is relevant but I've included it just in case. Can anybody explain these results? This as expected: >>> from django.db.models import Q,F, Sum, Count >>> from django.db.models.functions import Coalesce >>> from django.contrib.postgres.aggregates import StringAgg, ArrayAgg >>> qsx = MemDesc.objects.all().annotate( stocklines= Coalesce( Count('stock__qty'), 0), ... stocklevel= Coalesce( Sum('stock__qty'), 0)) >>> qs1 = qsx.filter(pk=140); o = list(qs1)[0]; o.stocklines 11 >>> o.stock.count() 11 Add ArrayAgg annotation, the stocklines annotation gets doubled. >>> qsx = MemDesc.objects.all().annotate( stocklines= Coalesce( Count('stock__qty'), 0), ... stocklevel= Coalesce( Sum('stock__qty'), 0) , ... partnumbers=ArrayAgg('productcode__code', distinct=True)) >>> qs1 = qsx.filter(pk=140); o = … -
Casting jsonb field's value as datetime field and then querying on it throws error
I have a model with jsonb field containing datetime value {'datetime': '2021-10-18 12:37:00.000Z'} but when I cast it using annotate(datetime=Cast('jsob__datetime', output_field=models.DateTimeField())) it throws the error 'DateTimeField' object has no attribute 'model' The model looks like this class Ticket(models.Model): jsonb = models.JsonField(default=dict) I am using Python 3.10 Django 3.2.8 Any suggestions? -
Django cached queryset.last() returns None object for not None object
My code is: @ttl_cache(maxsize=50, ttl=60 * 60) def get_query_set(): return Model.objects.all().order_by('year') def get_latest(): cached_qs = get_query_set() try: return cached_qs.last().year if len(cached_qs) > 0 else None except AttributeError: print('~~~~~~~~~~~~~~~~~') print('CHECK CIRCLECI PROBLEM') print(cached_qs) print(cached_qs.last()) print(len(cached_qs)) for aa in cached_qs: print(aa) print(type(aa)) print(dir(aa)) print(hasattr(aa, 'year')) try: print(aa.year) except Exception: print('no attr for aa') print(Model.objects.all().order_by('year')) for aaa in Model.objects.all().order_by('year'): print(aaa) print(aaa.year) print('~~~~~~~~~~~~~~~~~') raise Without try-except I getting (on get_latest()) AttributeError: 'NoneType' object has no attribute 'some_field' When I catch exception it print: ~~~~~~~~~~~~~~~~~ CHECK CIRCLECI PROBLEM <QuerySet [<Model: Model object (2)>]> None 1 Model object (2) <class 'path.models.model.Model'> ['DoesNotExist', 'Meta', 'MultipleObjectsReturned', '__class__', '__delattr__', ..., 'year'] True 2019 <QuerySet []> ~~~~~~~~~~~~~~~~~ So we can see that this problem is reproducible only at CircleCI build sometimes (I don't know how to reproduce it at local machine) cached queryset is not empty length of cached queryset is 1 queryset object is not None and has attribute year value of year is 2019 real object is already deleted at DB and does not exist (physically DB table is empty) non cached queryset is empty (because of ⑥) I guess that last() trying to re-get object from DB even if queryset is cached (because of queryset lazy behaviour?). … -
ConnectionError : Max retries exceeded with url: (Caused by ProtocolError('Connection aborted. ', OSError(0, 'Error')))
I am trying to work with the Django framework with Kerberos enabled. This is the piece of code where we had timeout added, which is now commented out. dont_wait = self.kwargs.get('dont_wait', False) kerberos_auth = '' if settings.KERBEROS_ENABLED is True: kerberos_auth=HTTPKerberosAuth(mutual_authentication=DISABLED, force_preemptive=True) if dont_wait is True: try: self.session.request( self.method, self.url, json=self.kwargs.get('data', {}), headers=self.headers, verify=settings.API_CERT_PATH, auth=kerberos_auth, #timeout=0.001 ) except exceptions.Timeout: pass else: return self.session.request( self.method, self.url, verify=settings.API_CERT_PATH, json=self.kwargs.get('data', {}), headers=self.headers, auth=kerberos_auth, ) I have also increased max_retries in this statement to 10 > requests.adapters.HTTPAdapter(max_retries=1) Still, on a few actions on the UI, I am getting below error. Traceback: File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 706. chunked=chunked, File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 382. self._validate_conn(conn) File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in _validate_conn 1010. conn.connect() File "/usr/local/lib/python3.6/site-packages/urllib3/connection.py" in connect 421. tls_in_tls=tls_in_tls, File "/usr/local/lib/python3.6/site-packages/urllib3/util/ssl_.py" in ssl_wrap_socket 429. sock, context, tls_in_tls, server_hostname=server_hostname File "/usr/local/lib/python3.6/site-packages/urllib3/util/ssl_.py" in _ssl_wrap_socket_impl 472. return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/lib64/python3.6/ssl.py" in wrap_socket 365. _context=self, _session=session) File "/usr/lib64/python3.6/ssl.py" in init 776. self.do_handshake() File "/usr/lib64/python3.6/ssl.py" in do_handshake 1036. self._sslobj.do_handshake() File "/usr/lib64/python3.6/ssl.py" in do_handshake 648. self._sslobj.do_handshake() During handling of the above exception ([Errno 0] Error), another exception occurred: File "/usr/local/lib/python3.6/site-packages/requests/adapters.py" in send 449. timeout=timeout File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" … -
Threads keep running in python django server
When I go to mywebiste/script, the script function runs and renders the json in the browser. list = [] def script(request): i = 0 urls = ["http://www.coden.live", "http://www.hackersvilla.xyz",] http = urllib3.PoolManager() threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls] for thread in threads: thread.start() for thread in threads: thread.join() return JsonResponse(list, safe=False) def fetch_url(url): http = urllib3.PoolManager() r = http.request('GET', url) soup = bs4.BeautifulSoup(r.data, 'html.parser') try: content = (soup.find("meta", {"name":"keywords"})['content']) list.append(content) except: print ("No meta keywords") It is displaying the data correctly. But when I refresh the page, data is displayed 4 times and so on -
Adding a Boolean Field in django taggit's model
I am building a Simple BlogApp and I am trying to add a custom Boolean Field field in whole django-taggit's base Model named TagBase. But I didn't find any information for adding a field in whole django-taggit. I am trying to add a Boolean Field with name (inbuilt) and slug (inbuilt). You can find the base (main) model of django taggit Here (django-taggit (models.py)). I also tried to extend directly from my created app's models.py models.py class TagBase(models.Model): name = models.CharField( verbose_name=pgettext_lazy("A tag name", "name"), unique=True, max_length=100 ) slug = models.SlugField( verbose_name=pgettext_lazy("A tag slug", "slug"), unique=True, max_length=100 ) boolean = models.BooleanField(default=False) But it didn't extend, it just made a new model. What I will do with Boolean Field ? I am trying to exclude about 40 tags in a query. But there isn't any boolean so i can make a difference of them. Any help would be much Appreciated. Thank You in Advance. -
How can I show the Django model in the html page I want?
I cannot display the model I created on a different page. It appears on the Model Admin page. Here models.py class Bonusrequest(models.Model): username = models.CharField(max_length=200,verbose_name="Kullanici Adi") name = models.CharField(max_length=200, verbose_name="Ad Soyad") created = models.DateTimeField(verbose_name="Tarih") And views.py from .models import Bonusrequest @login_required def finance(request): myModel = Bonusrequest.objects.all() return render (request,'pages/finance.html',{"Bonusrequest":myModel}) And here html page {% extends 'layoutdash.html'%} {% load static %} {% block content %} <section class="home-section"> <h1 class="c-grey-900 mT-10 mB-30">Test</h1> <hr> <table> <tr> <th>Name</th> <th>Username</th> <th>Country</th> </tr> {% for result in Bonusrequest %} <tr> <td>{{result.name}}</td> <td>{{result.username}}</td> <td>{{result.created}}</td> </tr> {% endfor %} </table> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </section> {% endblock %} What I want to do here is to show the values saved in the model on this page. What do you think am I missing? -
How to check if the request data is empty in Django rest framework?
I'm trying to write an APIView using django-rest-framework. In the post method I want to check if the request data contains anything, coz I often get KeyError. I can achieve it using the following code: if request.data is not None and request.data != {}: username = request.data["username"] Is there better way to write above code? Especially request.data != {} -
django.core.exceptions.ValidationError: ['“” value must be a decimal number.']
I got this error while migrating here is my models.py file: from django.db import models from django.conf import settings from decimal import Decimal # Create your models here. class Pharmacy(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Title = models.CharField(max_length=200) description=models.TextField() feed=models.DecimalField(max_digits=5,decimal_places=1,default=Decimal('1.0'),null=True) def __str__(self): return self.Title class feedback(models.Model): phid=models.ForeignKey(Pharmacy,on_delete=models.CASCADE) value=models.DecimalField(max_digits=5.,decimal_places=0,default=Decimal('1.0'),null=True) I did makemigrations with no errors -
I have multiple django views how do i integrate them with celery?
enter code here **views.py** from django import forms from django.contrib import auth from django.http import request from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render,redirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.generic import CreateView from .forms import DeveloperSignupForm,ProjectManagerSignupForm,TicketCreateForm from django.contrib.auth.forms import AuthenticationForm from .models import Developer, User,Ticket # Create your views here. def index(request): return render(request,'app/login_register_page.html') class developer_register(CreateView): model = User form_class = DeveloperSignupForm template_name = 'app/dev_register.html' def form_valid(self,form): user = form.save() return HttpResponse('<h1>Thank you for Registering,Please Login<h1>') class manager_register(CreateView): model = User form_class = ProjectManagerSignupForm template_name = 'app/pm_register.html' def form_valid(self,form): user = form.save() return HttpResponse('<h1>Thank you for Registering,Please Login<h1>') def manager_login(request): current = User.objects.filter(is_manager = True) if request.method == 'POST': pm_form = AuthenticationForm(data=request.POST) if pm_form.is_valid(): username = pm_form.cleaned_data.get('username') password = pm_form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: if user in current: login(request,user) return redirect(reverse('pm_dashboard')) else: messages.error(request,"Invalid Username or Password") else: messages.error(request,"Invalid Username or Password") return render(request, 'app/pm_login.html',context={ 'form':AuthenticationForm(), }) @login_required def pm_dashboard(request): return render(request,'app/pm_dash.html') def developer_login(request): current = User.objects.filter(is_developer = True) if request.method == 'POST': dev_form = AuthenticationForm(data=request.POST) if dev_form.is_valid(): username = dev_form.cleaned_data.get('username') password = dev_form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: if user … -
how to use different texts and logo for different tenants - django-tenants
i've created a project using [django-tenants][1] , and it currently use by some clients , but the problem is the have all the same invoice text , while they needs different text and logo in their invoices please is there a way to add different texts and logos per client ? here is my database configuration DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': 'my-app', 'USER':'postgres', 'PASSWORD':'postgres', 'HOST':'localhost', 'PORT':'5432' } } and my application SHARED_APPS = [ 'django_tenants','hotel', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users','rooms','vistors','booking','costs','payments','cancel',] TENANT_APPS = [ 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users','rooms','vistors','booking','costs','payments','cancel', ] INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] my tenant mixin application class Hotel(TenantMixin): hotel_name = models.CharField(max_length=40,unique=True) auto_create_schema = True auto_drop_schema = True logo = models.ImageField(upload_to=tenants_logo) def __str__(self): return self.hotel_name class Domain(DomainMixin): pass how to return back logos and add different texts for different clients please ? thank you in advance .. [1]: https://django-tenants.readthedocs.io/en/latest/install.html -
Django recieving DoesNotExist for http://127.0.0.1:8000/admin/
Tried to use djongo module for interacting django with mongodb: After applying manage.py createsuperuser Recieved the following error: djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT COUNT(*) AS "__count" FROM "account_emailaddress" WHERE ("account_emailaddress"."primary" AND "acc ount_emailaddress"."user_id" = %(0)s)',) Params: ((UUID('e7a7a962-7ab8-4c8d-9225-08e9aaa15b94'),),) Version: 1.3.6 Although I see the user created in mongodb. After trying to access admin endpoint I recieved: django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. -
Why model records are not displayed?
I ran into a system problem yesterday, the problem is that the model records are not displayed on the page, even though they were displayed before, I don’t know what the problem is, since everything worked before this is code views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) numbers = Number.objects.all() context['numbers'] = numbers return context this is code of html {% for number in numbers %} <h3 class="numbers">{{numbers.number1_text}}</h3> {% endfor %} {% for number in numbers %} <h3 class="numbers">{{numbers.number2_text}}</h3> {% endfor %} this is code of models.py class Number(models.Model): number1_text = models.CharField(max_length=200) number2_text = models.CharField(max_length=200) def __str__(self): return self.number1_text def __str__(self): return self.number2_text -
how to add html tag in django dictonary
I have added a strong tag in Django dict but not working mylist = [{'hq': 'abc', 'inst': 'Total', 'trade': 'Fitter'}] I added like this but it rendered the same not highlights mylist = [{'hq': 'abc', 'inst': '<strong>Total</strong>', 'trade': 'Fitter'}] -
How to get all event where user is member of a organization and event.organization is that organization?
Hi I am trying to get all event where user is member of a organization and event.organization is that organization. Here is my model's. class Organizer(TimestampedModel): name = models.CharField(max_length=100, null=False, blank=False) member = models.ManyToManyField(User, blank=False) class Event(TimestampedModel): name = models.CharField(max_length=250) organizer = models.ForeignKey( Organizer, on_delete=models.CASCADE, related_name="events", blank=False ) -
Django take multiple id on same model
hi first sorry for my bad english i am new on django, this is my first project. here the reference https://lookastic.com/men/white-hoodie/looks i want to create form on django admin that get multiple image from different product.py on django, here's the model Product.py model from django.db import models from .categories import Category from .brand import Brand class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) description = models.TextField(null=True) price = models.IntegerField(null=True) discount = models.IntegerField(blank=True, null=True) img1 = models.ImageField(max_length=200, upload_to='product_image', null=True) img2 = models.ImageField(max_length=200, blank=True, null=True, upload_to='product_image') img3 = models.ImageField(max_length=200, blank=True, null=True, upload_to='product_image') img4 = models.ImageField(max_length=200, blank=True, null=True, upload_to='product_image') img5 = models.ImageField(max_length=200, blank=True, null=True, upload_to='product_image') class Meta: verbose_name_plural = "products" def __str__(self): return self.name def __unicode__(self): return self.name OOTD.py model from django.db import models from .products import Product class Ootd(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='image_ootd') tag = models.CharField(max_length=200) desc = models.TextField() Image1 = models.ForeignKey(Product, on_delete=models.CASCADE) Image2 = models.ForeignKey(Product, on_delete=models.CASCADE) Image3 = models.ForeignKey(Product, on_delete=models.CASCADE) Image4 = models.ForeignKey(Product, on_delete=models.CASCADE) Image5 = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: verbose_name_plural = "OOTD" so in the model OOTD there's image 1-5, i want user add image that link to product, each image is different product so image 1-5 have unique product The link below …