Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to pass a name of button to views.py from jquery dialog
how to pass a name of button to views.py from jquery dialog? i want to pass like using jquery dialog to views.py how can i do that? could you help me up? my js in html function addcontinue(){ $('.confirm-continue-message').dialog({ dialogClass:"confirm-modal", modal: true, buttons: { "save and continue": function() { $('#addform').submit().attr("name", "save_add"); }, "cancel": function() { $(this).dialog('close'); }, }, resizeable : false, draggable: false, show: { effect: "fade", duration: 200 }, hide: { effect: "fade", duration: 200 }, focus:"none", }); } my views.py class StudentAdd(FormView): model = Student template_name = 'student/list_add.html' context_object_name = 'student' form_class = AddStudent def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): student = form.save(commit=False) student.created_by = request.user student.save() messages.info(request, student.name + ' 학생을 추가하였습니다.', extra_tags='info') if "save_add" in self.request.POST: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return redirect('student_detail', pk=student.pk, school_year=student.school_year) return FormView.post(self, request) -
How to associate existsing users from django.contrib.auth with Python Social Auth (Google backend)?
I have a Django app with a standard django.contrib.auth backend and have a lot of existing users, now I want to add login via Google account using Python Social Auth. Is there any way to allow login via Google account for existing users? How should I associate it with existing users? -
Getting Django - [Errno 111] Connection refused error
when Im trying to verify user registration via email its showing [Errno 111] Connection refused error in production but works fine in localhost settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'email-smtp.ap-south-1.amazonaws.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'xxx' EMAIL_HOST_PASSWORD = 'xxx' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'xxx' views.py def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your CaringHand Account' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': form}) error ConnectionRefusedError at /members/register/ [Errno 111] Connection refused please help -
Uploaded media to S3 bucket in AWS from django being routed to wrong URL
I am trying to use S3 bucket for media files in a production django project.The files are being uploaded to the bucket successfully but are not being fetched from the right url. Its trying to fetch from the domain rather than the S3 bucket URL. These are the two tutorials I am following: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ These are my current media settings for production: AWS_STORAGE_BUCKET_NAME = 'XXXXXXXXXXXXXX' AWS_S3_REGION_NAME = 'XXXXXXX' # e.g. us-east-2 AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXX' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_STORAGE = 'solvesto.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'solvesto.storage_backends.MediaStorage' STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATIC_URL = '/static/' from django.conf import settings class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION file_overwrite = False custom_domain = False class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION The static files work absolutely fine but the media is being routed to the wrong url. -
How to connect flutter Web_socket_channel package with Django Channels?
I want to connect the web_socket_channel package of Flutter with Django channel. My application is perfectly communicating using Django Template and Redis server. I want to use flutter package so that I can use this with flutter application. Django Channel Django API is using the following route: application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ path('ws/chat/<str:room_name>/', consumers.ChatConsumer) ]) ), }) JS WebSocket: My Django Template is using the following url path to connect websocket: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); Flutter: I've tried the following code with flutter to connect to Django Channel but failed. void startSocket() async { final channel = IOWebSocketChannel.connect('ws://$baseUrl/ws/chat/hello/'); channel.stream.listen( (event) { channel.sink.add('Received!'); channel.sink.close(status.goingAway); }, ); } I've seen some other peoples queries on the same topic and add the following permission to the AndroidMenifest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET"/> but flutter still it show the following errors: E/flutter ( 4901): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: SocketException: Failed host lookup: 'http' (OS Error: No address associated with hostname, errno = 7) E/flutter ( 4901): #0 new IOWebSocketChannel._withoutSocket.<anonymous closure> package:web_socket_channel/io.dart:84 E/flutter ( 4901): #1 _invokeErrorHandler (dart:async/async_error.dart:16:24) E/flutter ( 4901): #2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:282:9) E/flutter ( 4901): #3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:161:13) E/flutter ( … -
Google Account without cell Number
I am working on a bot, I want to create Gmail account with my bot but it is asking for the number and no skip option (skip number) is present there. guide me if there any way to do it any kind of help will be appreciated. thanks -
How to create Patient model with AbstractBaseUser, PermissionsMixin?
How to define Custom models more users with permissions? from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from django.contrib.auth.models import User, UserManager class PatientProfile(User): #id=models.AutoField(primary_key=True) first_name = models.CharField(_('first_name'), max_length=50, blank=True) last_name = models.CharField(_('last_name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) city=models.CharField(max_length=50) address=models.CharField(max_length=150) state=models.CharField(max_length=50) pincode=models.IntegerField() blood_groups=( ('A+','A+'),('O+','O+'),('B+','B+'), ('AB+', 'AB+'),('A-','A-'),('O-','O-'),('B-','B-'),('AB-','AB-'),) blood_group=models.CharField(max_length=10,choices=blood_groups) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_verified=models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=False) is_patient = models.BooleanField(_('active'), default=False) otp = models.IntegerField(null=True, blank=True) dob=models.DateField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # objects = MyUserManager() objects = UserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] #I got this errors django.core.exceptions.FieldError: Local field 'password' in class 'PatientProfile' clashes with field of the same name from base class 'User'. -
getting a huge null list on response while trying to upload through DRF
I am getting error while trying to upload files through POSTMAN here is the error and it is 26,000+ long. Although the uploaded files are being uploaded to the directory just fine but the return response is not . Any idea how to solve this? Uploaded media my models.py from django.db import models class Photo(models.Model): image = models.ImageField(upload_to='images/') class Audio(models.Model): audio = models.FileField(upload_to='audios/') class Video(models.Model): video = models.FileField(upload_to='videos/') my serializers.py from rest_framework import serializers from .models import Photo, Audio from rest_framework import status from rest_framework.response import Response class ImageListSerializer(serializers.Serializer): image = serializers.ListField( child=serializers.FileField(max_length=100, allow_empty_file=False, use_url=True)) def create(self, validated_data): image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img) print(photo) return photo class Meta: model = Photo fields = ('pk', 'image') class AudioListSerializer(serializers.Serializer): audio = serializers.ListField( child=serializers.FileField(max_length=100, allow_empty_file=False, use_url=True)) def create(self, validated_data): audio=validated_data.pop('audio') for aud in audio: sound=Audio.objects.create(audio=aud,**validated_data) print (sound) return sound class Meta: model = Audio fields = ('pk', 'audio') my views.py from django.shortcuts import render from rest_framework import viewsets, mixins, status from rest_framework.settings import api_settings from .models import Photo, Audio from .serializers import ImageListSerializer, AudioListSerializer from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response class PhotoViewSet(viewsets.ModelViewSet): serializer_class = ImageListSerializer parser_classes = (MultiPartParser, FormParser,) queryset = Photo.objects.all() class AudioViewSet(viewsets.ModelViewSet): serializer_class = AudioListSerializer parser_classes = … -
how can I build screen sharing an application with controlling, voice functionalities using python and webRTC [closed]
I want build screen sharing an application from the scratch. Which I need to include other functionalities like remote controlling and audio and video calling(like zoom app) using python with help of webRTC in Django framework. This is my task in this I have some restriction need not use Node JS, React JS and other libraries. -
Login redirecting to specific page based on specific group in template
I have two admin groups in django-admin[staff, student]. I want that whenever a user wants to log in, the program first checks that to which group the user belongs, then redirect each one to a particular page. index.html <form method="post" action="{% url 'users:login' %}" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary mt-2">Log in</button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'student_paper:index' %}" /> </form> -
error when query django database: ValueError: The annotation 'code' conflicts with a field on the model
I use Django2 and sqlite in windows 10 for a course management website. when I tried to query the database in view.py using query_results_3 = CourseInfo.objects.values('title', code=course_code[:5]) error occurs: ValueError: The annotation 'code' conflicts with a field on the model. model.py: class CourseInfo(TimeStampedModel): # school or center code = models.CharField(max_length=20, unique=True, db_index=True) title = models.CharField(max_length=200) school = models.ForeignKey(School, on_delete=models.SET_NULL, blank=True, null=True) postgraduate = models.BooleanField(default=False) # indicate Postgraduate course discipline = models.ForeignKey(Discipline, on_delete=models.SET_NULL, blank=True, null=True) # should not be null pattern = models.CharField(max_length=120, choices=PRESENTATION_PATTERN, blank=True, null=True, help_text="Presentation Pattern") type = models.CharField(max_length=2, choices=(('PT', 'Part-Time'), ('FT', 'Full-Time'), ('OL', 'Online'))) available = models.BooleanField(default=True) # mean Active or Retired semesters = models.ManyToManyField('Semester', through="Course") # auto have semestercourse_set def __str__(self): return "{} - {}".format(self.code, self.title) class Meta: constraints = [models.UniqueConstraint(fields=['code', 'type'], condition=models.Q(available=True), name='unique_course_type')] ordering = ['code', ] How to change my code to let the error disapear? -
How to keep Django site on? [closed]
I created my Django website and it is working fine, but when i close my command prompt the site stops working how do get rid of this problem? -
How to pass file's content as CharField in django model?
I have a model for icon, which looks like this: class Icon(models.Model): name = models.CharField(max_length=50) icon = models.FileField(upload_to='icons/', blank=True, null=True) inline_svg = models.CharField(max_length=1000, blank=True) Most of files are .svg and I want to pass into inline_svg content of corresponding file to use inline svg on front-end. How can i do that? Or maybe there is any better variants to do what I want? Also had an idea of something like this: class Icon(models.Model): def svg(self): f = open(self.icon.url) return f.read() name = models.CharField(max_length=50) icon = models.FileField(upload_to='icons/', blank=True, null=True) inline_svg = models.CharField(max_length=1000, default=svg()) -
Django/React set-cookie: csrftoken and X-CSRF-Token do not match and persists
I've been working through the nightmare that is decoupled React/Django and can't seem to figure out why my CSRF tokens, 1) do not match in the response, and 2) why the cookie is persisting between refreshes. Django View: def get_csrf_token(request): response = JsonResponse({'detail': 'CSRF cookie set'}) response['X-CSRFToken'] = get_token(request) return response Django CSRF Settings: CSRF_COOKIE_SAMESITE = 'Strict' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_AGE = None React CSRF API Call: getCSRF = () => { fetch("/api/csrf/", { credentials: "same-origin", headers: { "Cache-Control": "no-cache, no-store, max-age=0, must-revalidate" } }) .then((res) => { let reqCsrfToken = res.headers.get("X-CSRFToken"); this.setState({csrf: reqCsrfToken}); }) .catch((err) => { console.log(err); }); } Now, the problem is that every time I ping the view with this call, the response headers between the set-cookie and the x-csrftoken will be totally different. Additionally, the original cookie value will persist across new calls and refreshes. set-cookie: csrftoken=KceWlQsdiQuM....... vs the X-CSRFToken Value x-csrftoken: Ymx3NCe5dwh....... I've checked and printed and logged everywhere, and the cookie value is always different. -
How to create REST viewset for following models.py and serializers.py? i am new with django rest framework
I created an REST API which generate coupon codes, but now i like to redeem/Validate coupon code using Postman, HTML, Python script so anyone can help me to create ViewSets for this models.py and serializers.py file, I am new with django so please little detaild explanation. Thank you Here is my models.py file :- from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my serializers.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Also if there are any mistakes in my code please tell. -
django including URLconf missing argument: 'view'
I'm starting right now with learning Django and I wanted to include a URLconf. I did it like in the comment on the top of the urls.py file. My urlpatterns: urlpatterns = [ path('home/', include('api.urls')) ] This throws me an Error: TypeError: _path() missing 1 required positional argument: 'view' So now I'm asking what is wrong because in the 'documentation' it says: Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) Please help -
Django request.user is still authenticated after logging out
I have a reactjs app with Django as backend. There's a page that has a toggle which makes an API call to the backend updateIsPaid: id => instance({ 'method': 'POST', 'url': BACKEND_RECEIPTS_LIST_URL + id + '/', 'data': id }), and in the backend class ReceiptDetailView(APIView): permission_classes = (permissions.,) def post(self, request, *args, **kwargs): receipt_id = kwargs['id'] receipt = Receipt.objects.get(id=receipt_id) receipt.is_paid = not receipt.is_paid receipt.save() return Response(receipt_id, status=status.HTTP_200_OK) What I've noticed is that when I log out the user in frontend, which destroys the auth token and username stored in localstorage as well as calling django logout in the backend, when i hit the back button and jump back to the page with the toggle, I can still make the POST call and the result is still 200. What I was expecting is the POST call would return a 401. Further investigation shows that the user, while being logged out, the user still passes the IsAuthenticated perm check. This really confuses me and I don't know how to block the accessibility of such user upon logout. Any idea? -
Django upload file + main thread
I'm new to django. I have a question: django is a synchronous framework. Is the main thread blocked when the client sends a file to the server? -
How do I add username of logged in user to model field in django..?
class CustomUser(AbstractUser): email = models.EmailField(unique=True,blank=True,max_length=254, verbose_name='email address') phone_number = models.IntegerField(blank=True,null=True,verbose_name="phone number") ids = models.UUIDField(blank=True,null=True,default=uuid.uuid4, editable=False) parent_id = models.IntegerField(blank=True,null=True) role_id = models.IntegerField(default = auto_increment) I have created a parent_id field in Django customeUser(AbsractUser) Model.I want to populate this field by primary key of the user who is adding the new user in customUser model and the data of user who is adding the new user is in same model only. Thanks in Advance.. -
Django: Zipped file download issue
I got an error : FileNotFoundError at /test/ [Errno 2] No such file or directory: '[' This is an error that might be with the query string in the template or anything else. def submit(request): paths = [list of filenames] context = {'paths' :paths} def test_download(request): paths = request.GET.get('paths') context ={'paths': paths} response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in paths: zip_file.write(filename) zip_file.close() response['Content-Disposition'] = 'attachment; filename='+'converted files' return response templates <p> <a href ="{% url 'test_download' %}?paths={{ paths|urlencode }} " download>Converted Files</a> </p> <br> Help me to find the issue here. -
(DRF) Why make a query before create when unique=True?
I have User model and serializer class which represents it. class User(models.Model): username = models.CharField(unique=True, max_length=50) is_admin = models.BooleanField(default=False) class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = (“username”, “is_admin”) def create(self, validated_data: Dict[str, Any]) -> User: username = validated_data["username"] try: user_object = User.objects.create(username=username) except IntegrityError: raise UserAlreadyRegistered() return user_object My database holds lots of users(appr. 10 million). When I create another user, Django Rest Framework look at the model fields and check that if there are any unique=True fields. If there are, then it assigns “UniqueValidator”. This validator calls “filter_queryset” which means it query the database and check that are there any given username record. If there are not, then it creates the user. My question is, why DRF make a query before create operation? Since database(PostgreSQL) holds the field attributes, it knows that username field is unique, and it can throw an exception if I try to create user with the same username field. The reason I’m asking it, my application gets a lot of create operation, and each create operation I have to query my database, which is I think more costly than create it wihout making a filter query. Do I missing something in this operation? … -
Page not found when trying to use Django url routing
So I've been trying to use django dynamic url routing but when I try to open the link, Django shows me that the page was not found (error 404). Here's my urls.py: from django.urls import path from pages.views import home_view, contact_view from products.views import ( product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view ) urlpatterns = [ path('', home_view, name = 'home'), path('contact/', contact_view, name = 'contact'), path('product/<int:my_id>', dynamic_lookup_view, name='product'), path('create/', product_create_view), path('admin/', admin.site.urls), ] Here's my views.py (Only included the main function which I'm trying to render right now): from django.shortcuts import render from .models import Product #from .forms import ProductForm, RawProductForm # Create your views here. def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/product_detail.html", context) When I'm trying to open the /product/ I get the error. Can anyone tell me what I'm doing wrong? This is the error: Request Method: GET Request URL: http://127.0.0.1:8000/product/ Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order: [name='home'] contact/ [name='contact'] product/<int:my_id> [name='product'] admin/ The current path, product/, didn't match any of these. -
httpd with django3 with python3.6 on Centos7
need urgent help. we are trying to run django3 (python3.6 on Centos7) with httpd. i get following error when i run it by HTTPD. [Tue Jan 12 06:52:04.575618 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] Traceback (most recent call last): [Tue Jan 12 06:52:04.575665 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/srv/django/django/wsgi.py", line 16, in <module> [Tue Jan 12 06:52:04.575670 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] application=get_wsgi_application() [Tue Jan 12 06:52:04.575678 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Jan 12 06:52:04.575682 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] django.setup(set_prefix=False) [Tue Jan 12 06:52:04.575690 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Tue Jan 12 06:52:04.575694 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Jan 12 06:52:04.575701 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ [Tue Jan 12 06:52:04.575706 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] self._setup(name) [Tue Jan 12 06:52:04.575713 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup [Tue Jan 12 06:52:04.575717 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] self._wrapped = Settings(settings_module) [Tue Jan 12 06:52:04.575724 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ [Tue Jan 12 06:52:04.575729 2021] [wsgi:error] [pid … -
My generic Django ListView only updates once the user has logged out. How can I get it to auto-update?
I have a model called Strategy class Strategy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) organisation = models.CharField(max_length=20, default="Enter Text Here") strategy_name = models.CharField(max_length=20, default="Enter Text Here") summary = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-created_date"] verbose_name_plural = "strategies" @property def name(self): return "%s - %s" % (self.organisation, self.strategy_name) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('strategy_detail', args=[str(self.id)]) There are two views associated with the model. A ListView: class StrategyListView(ListView): model = Strategy context_object_name = 'strategy_list' template_name = 'simulator/strategy_list.html' And a FormView: class StrategyDefineView(FormView): template_name = 'simulator/strategy_define.html' form_class = StrategyForm success_url = '/simulator/' def get_initial(self): initial = super().get_initial() initial['user'] = self.request.user return initial def form_valid(self, form): form.save() return super().form_valid(form) When the user submits a form from the FormView, they are returned to the ListView. My problem is the ListView doesn't update until the user logs out and logs back in. So, if I submit a form on the FormView, I'm returned to the ListView where I don't see my submission. However, if I'm logged in as superuser, the ListView will update without the user logging out if I go to admin and then return to the ListView page. Does anyone know how I can … -
Removing Null nested fields in Django Serializer --- or how to iterate with Null?
This issue I am having is likely a React iteration problem but I think taking care of it at the root inside Django will be more efficient instead of on the front end. Possible remedies: ternary operation to conditionally display objects and parameters if not null remove null fields from response to avoid needing to do ternary operation through django itself Although, in the first place, I cannot seem to be able to iterate through my response. I have a double nested serializer: Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class VideoProduct(models.Model): ... class ImageProduct(models.Model): ... class ProfileProduct(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) video_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True) image_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True) class Meta: unique_together = ('profile', 'video_product') unique_together = ('profile', 'image_product') Views.py: class VideoProductViewSet(viewsets.ModelViewSet): queryset = VideoProduct.objects.all() serializer_class = VideoProductSerializer class ImageProductViewSet(viewsets.ModelViewSet): queryset = ImageProduct.objects.all() serializer_class = VideoProductSerializer class ProfileProductsViewSet(viewsets.ModelViewSet): queryset = ProfileProduct.objects.all() serializer_class = ProfileProductsSerializer class ProfileBySlug(generics.ListAPIView): serializer_class = ProfileBySlugSerializer def get_queryset(self): slug = self.request.query_params.get('slug', None) queryset = Profile.objects.filter(slug=slug) if slug is not None: queryset = queryset.filter(slug=slug) return queryset Serializers: class VideoProductSerializer(serializers.ModelSerializer): class Meta: model = VideoProduct fields = ['id', 'price'] class ImageProductSerializer(serializers.ModelSerializer): class Meta: model = ImageProduct fields = ['id', 'price'] class ProfileProductsSerializer(serializers.ModelSerializer): video_product = VideoProductSerializer(read_only=True) image_product …