Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use redis-sentinel?
Can Anyone please explain the working of this redis sentinel with master-slave configuration as explained in the image below. -
django LoginView redirecting to accounts/profile instead of success_url
I have two user types usertype a and user type b i am trying to create a two seperate login forms and views using AuthenticationForm and Loginview i am getting redirected to accounts/profile after logging in forms.py class myForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: user = authenticate(self.request, username=username, password=password) if user is None: raise self.get_invalid_login_error() else: if user is not None: if user.usertype_a: login(self.request,user) return self.cleaned_data views.py class MyLoginView(LoginView): template_name = 'log.html' form_class = myForm success_url = reverse_lazy("home") -
Error installing a django project AttrributeError: module 'collections' has no attribute 'Iterator'
i am trying to use this project https://github.com/tangjon/Build-a-PC-Configuration-Tool but i have an error in the process. First of all i am cloning the project using this command: git clone https://github.com/tangjon/Build-a-PC-Configuration-Tool.git after that i am changing directory and go to: cd Build-a-PC-Configuration-Tool installing the requirements: pip install -r requirements.txt change directory again to go into the manage.py for migrations: cd bapccanada then migrate: python manage.py make migrations and here is the error AttributeError: module 'collections' has no attribute 'Iterator' enter image description here Any ideas to solve the error? Thank you in advance! -
Django: How to trigger a function whenever certain objects are modified from the wagtail interface
I have a long list of "Quotation" objects. The price of a quotation depends on dozens of children (and grand children) objects. The lowest one being the rate/hour. When I change the children objects of a quotation like the rate/hour, the quotation price changes. I would like to recalculate the price of each quotation that is impacted by any change I make on their consistuant objects automatically. I am using Wagtail for the object admin. I am not sure about the way to do that, should I use signals? Wagtail hooks? -
how to put data from a form submition (get method) into a dictionary - ajax
I'm trying to send some data to backend the data is from date type inputs here is my template $(document).ready(function(){ const datainputs = new FormData(); $('#date_form').submit(function(e){ datainputs.append('from',document.getElementById('from').value) datainputs.append('to',document.getElementById('to').value) e.preventDefault(); }) console.log(datainputs)//returns empty function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:datainputs, success:function(data){ const datetimes = data; console.log(datetimes) spinner.setAttribute('hidden',true); var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=2>not found</td>' } k+='</tbody>' document.getElementById('datetime_prices_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" method="GET" id="date_form"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 mx-auto text-left row"> from <input type="date" class="form-control col-9 mr-1" name="from" id="from"> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> to <input type="date" name="to" class="form-control col-9 mr-1" id="to"> </p> <button type="submit" class="btn btn-info col-8 col-sm-5 col-md-3 mx-auto">search</button> </div> </form> in the console returns empty values in formData ! i've to send the two date to backend if the two date exists if not, it will return the entire data and here is my backend - django def priceByDateTime(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') … -
how to filter multiple messages in django
so i recently did a filter for messages so as to bring all the messages between two people def pmessage(request, pk): user = User.objects.get(id=pk) message = pm.objects.filter(Q(receiver=request.user, sender=user) | Q(receiver=user, sender=request.user)) form = dmform() context = { 'message' : message, 'form' : form, } it works, only that it groups the messages in categories ie, it would list all the messages that meets one criteria before the other irrespective of which message came first, and that defeats my aim. thanks you -
on using instence= (class name) <django.db.models.query_utils.DeferredAttribute object at 0x00000256CA7C05E0>
views.py geting path in output instide of values present in it I am trying but not gating answers please provide me some suggestions from django.shortcuts import render from django.http import * from MYapp.models import * from .form import * def venue(request): venue_list = Task.objects.all() return render(request,'MYapp/venue.html',{'venue_list': venue_list}) def navebar(request): return render(request,'MYapp/navebar.html') def db(request,db_id): venues = Task.objects.get(pk=db_id) return render(request,'MYapp/db.html',{'venues': venues}) def search(request): if request.method =="POST": searched = request.POST.get('searched', False) Tasks =Task.objects.filter( firstname__contains = searched) return render(request,'MYapp/search.html',{'searched':searched, 'Tasks':Tasks}) else: return render(request,'MYapp/search.html',{}) def update(request,db_id): venues = Task.objects.get(pk=db_id) form = TaskForm(request.POST or None, instance=Task) return render(request,'MYapp/update.html',{'venues': venues,'form':form}) -
Django - Deleting using modal: show and delete only the first item from the table
Please help me understand the problem. I try to use the modal to delete each line separately but instead of displaying and deleting my actual line, it always displays and deletes the first line in the table. Where am I wrong with the code? Below my settings. Thank you very much. models.py class Post(models.Model): class DisplayOnlyPublicat(models.Manager): def get_queryset(self): return super().get_queryset() .filter(status='publicat') options =( ('draft', 'nepublicat'), ('publicat', 'publicat') ) title = models.CharField(max_length=250) poster = models.ImageField ( upload_to ='posts/', default='posts/poster_articole_pp.jpg') category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) author = models.ForeignKey (User, null=True, on_delete=models.SET_NULL, related_name='profipedia_posts') short_content = models.TextField(null=True) # content = models.TextField() # content = RichTextField() content = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/vendor/ckeditor_plugins/emojione/' , 'plugin.js', )],) status = models.CharField(max_length=10, choices=options, default='draft') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) objects = models.Manager() #denumire initiala dop = DisplayOnlyPublicat() # denumire custom def get_absolute_url(self): return reverse('posts:articol', args=[self.slug]) # sa deschida articolul pe baza de denumire(slug) din sectiunea admin indiferent de statusul articolului (publicat/nepublicat) # def get_absolute_url_adm(self): # return reverse('posts:articolAdm', args=[self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title views.py def delete_articol(request, articol_id): post = Post.objects.get(pk=articol_id) post.delete() messages.success(request, "Articolul a fost sters!") return redirect('posts:articoleAdm') urls.py urlpatterns = [ path('', views.articole, name='articole'), path('articole-admin/', views.articoleAdm, name='articoleAdm'), … -
Specify the pages that navbar items should appear on with Bootstrap in Django
I am trying to specify the page that this navbar dropdown should appear on. I tried adding this line: {% if request.resolver_match.url_name == 'club_selection' %} class = "active" {% endif %} but that doesn't seem to do anything for me. Maybe I am using it wrong. If anybody knows how to do this correctly it would be a massive help. club_selection_dropdown.html <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item dropdown"> <li {% if request.resolver_match.url_name == 'club_selection' %} class = "active" {% endif %}> <a class="nav-link" href="/" id="club--dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Current Clubs <span class="bi-arrow-down-circle-fill"></span> </a> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="club-dropdown"> {% for club in clubs %} <form action = "{% url 'group_check' user.id %}" method = "post"> {% csrf_token %} <input type="hidden" name="club_name" value="{{ club.club_name }}"> <style> .btn:hover { background-color: lightgrey; } .btn-group.special { display: flex; } .special .btn { flex: 1; } </style> <div class="btn-group special" role="group"> <input type = "submit" value = "{{club.club_name}}" class="btn col-xs-11 text-left" style=".btn-primary:hover; text-align:left; padding-left:6px"> </div> </form> {% endfor %} </ul> </li> </li> </ul> </div> views.py def club_selection(request): list_of_clubs = ClubList() clubs = list_of_clubs.club_list return render(request, 'club_selection.html', {'clubs':clubs}) -
Appointment booking system. Avoid double bookings
I am currently trying to build an appointment system. This works fine however the function doesn't catch if the same appointment has already been booked in the models. class BookingView(FormView): form_class = AvailabilityForm template_name = "availability.html" def form_valid(self, form): data = form.cleaned_data bookingList = Appointment.objects.filter() for booking in bookingList: if booking.start > data["end_time"] or booking.end < data["start_time"]: booking=Appointment.objects.create( name=data["name"], start=data["start_time"], end=data["end_time"] ) booking.save() print(booking.start) print(data["start_time"]) return HttpResponse("can be booked") else: print(booking.start ) print(data["start_time"]) return HttpResponse("Cant be booked") -
How to test GET and POST api which requires user logged in pytest Django?
I have created a fixture to create user in conftest.py @pytest.fixture def test_password(): return 'strong-test-pass' @pytest.fixture(scope='session') def create_user(db, test_password): def make_user(**kwargs): employee = e_ge_employee.objects.create() kwargs['password'] = test_password if 'username' not in kwargs: kwargs['username'] = str(uuid.uuid4()) if 'employee' not in kwargs: kwargs['employee'] = employee return e_ge_user.objects.create(**kwargs) return make_user and then wrote a testcase to check login in test_urls.py @pytest.mark.django_db def test_auth_view(client, create_user, test_password): user = create_user() url = '/accounts/login/' client.login( username=user.username, password=test_password ) response = client.get(url) print("RESPONSE - ",response) assert response.status_code == 200 Now I want to write a test case to test GET and POST API and the APIs will only work if the user is authenticated, Can someone please provide me with the solution.....Thanks in Advance -
Render html content stay on current page with form action set to different url in Django
My question is there is a way to render html content(bootstrap alert) on the current page(1st page) with POST action set to a different url(2nd page)? I have following content in views.py: def calendar(req): # 1st page return render(req,'calendar.html') def result(req): # 2nd page if req.method == 'POST': xxx else: no_data = "xxx" context = { 'no_data': no_data } return render(req, 'calendar.html', context) xxx return render(req,'result.html',context) The form info is submitted to different url(2nd page) in calendar.html: {% if no_data %} <div class="alert alert-warning" role="alert"> {{ no_data }} </div> <form action="{% url 'result' %}" method="POST"> Thank you. -
How to migrate remote postgres db into my local django project?
I am creating a Django project where I have to use existing database data. The existing database is Postgres and it is hosted on Aws. My goal is to copy them from Aws to my local Postgres DB and use in my project. Thanks -
Django using Amazon S3
So whenever I run the following a staticfiles folder gets created and I can't collectstatic to my AWS S3 bucket. (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> python manage.py collectstatic Found another file with the destination path 'user\main.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'storages', ] STATIC_ROOT = 'static/' # All of this is in my console.aws.amazon to configure aws s3 static files only # IAM Management Console AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Typescript endpoint to list users in Django
So I have a Django project and I want to create a typescript endpoint to list which users live in a certain postal code. I have never used typescript so I don't know how to create it and integrate it with the django project. Help is much appreciated. the models.py if it is useful: class UsuarioMaster(models.Model): nombre = models.CharField(max_length=50) class UsuarioDetalle(models.Model): usuario = models.ForeignKey(UsuarioMaster, on_delete=models.CASCADE, null=True) codigo_postal = models.CharField(max_length=5) ciudad = models.CharField(max_length=50) pais = models.CharField(max_length=50, default='') -
How do I create a QR code in Python without saving it as an image
I am trying to make Qr Codes using Python on a Django applicaiton using this code : def generate_qr_code (reference): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4, ) qr.add_data(reference) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white").convert('RGB') filename = reference+".jpeg" img.save("C:\\qrs\\"+filename) Now, this function is called when I click on a "Generate Qr Code" Button. My problem is that I would like the Qr Code to be displayed on a new tab on my browser instead of it being saved as an image, as I only need to print them on paper at that moment and I have no need to keep the images. Thank you for your help. -
facing some issues while installing the mysqlclient Django
i am facing some issues while installing the mysqlclient in virtual environment sudo apt-get install python3-mysqldb sudo apt-get install libmysqlclient-dev -
How to access Django secret key when git cloning from github?
So I have placed Django secret key in base.json and added that in .gitignore to prevent push and pulls to github and edited settings.py accordingly as such. Problem is that I am trying to deploy my api to AWS ec2 and when I git clone on my Ubuntu terminal, obviously that base.json file is missing and I cannot run my code because secret key is not found. So what should I do in this case? settings.py: import os, json from django.core.exceptions import ImproperlyConfigured secret_file = os.path.join(BASE_DIR, 'base.json') with open(secret_file) as f: secrets = json.loads(f.read()) def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = "Set the {} environment variable".format(setting) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_secret("SECRET_KEY") DEBUG = False ALLOWED_HOSTS = ['*'] I have seen How to access Heroku config variables inside Django settings and other similar ones but they all relate to Heroku and not my case. -
module 'collections' has no attribute 'MutableMapping'
i am trying to upload images from admin page to the data base, in django project i have configured and i have tried many ways to fix this but doesn't worked please guide me:- settings.py MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR / 'media') urls.py urlpatters[...] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py product_img = models.ImageField('Product Image', upload_to = 'product_img', blank=True ) docker file FROM python:3.9.7-alpine3.14 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirement.txt /app/ RUN pip3 install -r requirement.txt COPY . /app/ requirments.txt Django==3.2.9 Pillow==2.2.1 -
Python sorted object
I have query that is sorted via python however I would like to exclude the brands with the distance greater than 100km this is what I wrote, however it always gets distance that is beyond 100km return sorted( root.brands.filter(status=True, region_id=area), key=lambda qs: (qs.distance(**kwargs) <= 100, qs.distance(**kwargs) < 100 if qs.distance(**kwargs) > 0 else []) ) is there any way to do this? thanks -
NoReverseMatch at / Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/$']
Please somebody help please, am new to Django and don't know how to get around this in my code. Am following a tutorial and that builds a chatroom with Django. Everything works fine but then I wanted to modify it and display the posts written by a user on their profile page so that others can see it, but instead i got this error 'NoReverseMatch at / Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$'] Here is my View file; from django.shortcuts import render, redirect from django.http import HttpResponse #from django.urls import reverse from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.db.models import Q from .models import Message, Room, Topic from .forms import RoomForm def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() context = {'user': user, 'rooms': rooms} return render(request, 'base/profile.html', context) here is my URL: from django.urls import path from . import views urlpatterns=[ path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name='user-profile'), ] 'Error during template rendering' In template C:\Users\Nonesi\Desktop\StudyBudy\base\templates\base\feed_component.html, error at line 9 so here is my template: <div> {% for room in rooms %} <div> {% … -
getting 127.0.0.1 refused to connect. when try to add new fk in django admin
Hi i am always getting 127.0.0.1 refused to connect. error on popup when i tring to add new fk in existed model using + in django admin . is i am using "admin_interface",and some other package also i tried which are in installed apps ,is that reason that i am getting this error. i try to pass "*" in ALLOWED_HOSTS in setting.py , when i am trying that process in google chrome browser it show as i share in image 1 but when i tring to do same with firefox it is shared in second image . my setting.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ # 'grappelli', "admin_interface", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mdeditor', "colorfield", 'drf_yasg', "rest_framework", 'django_filters', "corsheaders", "storages", 'rest_framework_swagger', 'authentication', 'mails', 'authors', 'book_store', 'institude_home_page', ] 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', ] ROOT_URLCONF = 'vani_prakashan.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'vani_prakashan.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'apps.authentication.backends.JWTAuthentication', # … -
how to send input date value from template to backend through ajax request - django
i've to make a query base on two dates, if the dates exists, if not just run the query without any filtration, but i dont know how send the dates input value from client side to server side , here is my views def priceByDateTime(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) else: datetimes = MyModel.objects.all().annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) return JsonResponse(datetimes,safe=False) @login_required def queryTemplate(request): return render(request,'myapp/datetimes.html') i know how to make the query dont sure how send the input date type values to backend and here is my GET form, to get the two date from $(document).ready(function(){ const start_date = new Date($('#from').val()); const end_date = new Date($('#to').val()); console.log(start_date) console.log(end_date) if(start_date && end_date){ data={ 'from':start_date, 'to':end_date } } function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:data, success:function(data){ const datetimes = data; var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=6>found nothing</td>' } k+='</tbody>' document.getElementById('datetime_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" … -
How to keep current url including parameters in JavaScript
I am using the modal to edit data by using the code below, and when I click the 'Change' button, I want to keep the current url. Even when I set a parameter, I don't want me to lose the parameter. This url has no parameters set. So, if I edit data in modal and click the 'change' button, I lose all the parameters I set and return to the initialized screen. I am using Django and python, and I am getting parameter values through request.POST.get method in views.py . function (data, status, xhr) { let code = data.code if (code === 'error') { for (let i in fields) { let key = fields[i]; let labelElement = editForm.find('label[for=' + key + ']'); let container = labelElement.parent(); if (key in data.error) { container.addClass('card-inverse-danger'); const msg = data.error[key][0]; let text = $('<div class="text-danger small" style="line-height: 1rem;">' + msg + '</div>') labelElement.find('.text-danger').remove(); labelElement.append(text); } else { container.removeClass('card-inverse-danger'); labelElement.find('.text-danger').remove(); } } } else if (code === 'success') { window.location.href = '/study/help/'; --> I think I need to update this line. } }) -
I am unable to serialize my product images in Django Rest Framework
I am trying to create product model for my e-commerce app in Django rest framework, and I am able to upload images to my products on the admin panel but I am unable to get their links while calling the API. Here's my: models.py from django.db import models from api.category.models import Category from api.color.models import Color from api.size.models import Size class Product(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) regular_price = models.CharField(max_length=50) sell_price = models.CharField(max_length=50, blank=True, null=True) stock = models.CharField(max_length=50) is_active = models.BooleanField(default=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'images/') def __str__(self): return self.image.url serializer.py from django.db.models import fields from rest_framework import serializers from .models import Product, ProductImage class ImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image', ) #print(model) class ProductSerializer(serializers.HyperlinkedModelSerializer): colors = serializers.StringRelatedField(many=True) sizes = serializers.StringRelatedField(many=True) image = ImageSerializer(many=True, read_only=True) class Meta: model = Product fields = ('id', 'name', 'description', 'regular_price', 'sell_price', 'category','colors', 'sizes', 'image') admin.py from django.contrib import admin from .models import Product, ProductImage class ProductImageAdmin(admin.StackedInline): model = ProductImage @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] class Meta: model …