Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RestFramework - Test View failing with 400
right now I'm trying to create a simple test-file for a ListCreateAPIView inside my views.py: views.py: class AuthorListCreateView(ListCreateAPIView): queryset = Author.objects.all() serializer_class = AuthorSerializer serializers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' urls.py: urlpatterns = [ path('author/', AuthorListCreateView.as_view(), name='author-list'), ] models.py from django.contrib.auth import get_user_model USER = get_user_model() class BaseModel(models.Model): id = models.BigAutoField(primary_key=True, editable=False, unique=True) created_by = models.ForeignKey(USER, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True get_latest_by = 'created_at' class Author(BaseModel): class Gender(models.TextChoices): NO = 'NO', 'No gender chosen' DIVERSE = 'DI', 'Diverse' FEMALE = 'FE', 'Female' MALE = 'MA', 'Male' first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) born = models.DateField(null=False, blank=False) died = models.DateField(null=True, blank=True) passed = models.BooleanField(default=False) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.NO) slug = models.SlugField(null=False, blank=False, unique=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name='unique_name_constraint'), ] indexes = [ models.Index(fields=['last_name', 'first_name'], name='index_unique_name'), ] verbose_name = 'Author' verbose_name_plural = 'Authors' def __str__(self) -> str: return f'{self.first_name} {self.last_name}' def save(self, *args, **kwargs): self.passed = True if self.died is not None else False self.slug = slugify(f'{self.last_name}-{self.first_name}') if not self.slug else self.slug super(Author, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('author-detail', kwargs={'slug': self.slug}) def clean(self): if self.died is not None … -
Django - TypeError at /api/v1/latest-products/ FieldFile.save() got an unexpected keyword argument 'quality'
I don't know why, but every time I try to go to the API URL, I keep getting this error message, I think the problem is in one of these modules, but I don't know what to change. models.py module found in the product package from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if self.thumbnail: return 'http://127.0.0.1:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.make_thumbnail(self.image) self.save() return 'http://127.0.0.1:8000' + self.thumbnail.url else: return '' def make_thumbnail(self, image, size=(300,200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() image.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail I think the problem is found in the make_thumbail function or the get_thumbnail function? serializers.py module found in … -
Gunicorn is throwing Out of Memory with max request and max requests jitter
Gunicorn is throwing Out of Memory I have tried to add max request and max requests jitter but still getting Out of Memory. Gunicorn is being controlled by supervisor exec gunicorn myproject.wsgi:application --bind unix:/webapps/run/myproject/gunicorn.sock --max-requests 500 --max-requests-jitter 50 --workers 3 --timeout 300 --user=root --group=webapps I have tried to check the gunicorn process ID it consumes 95% of memory out of 20GB and started 18 hours ago what I am doing wrong. Any help appreciated -
Can I check my backend code on Django without a frontend?
I'm new to Django and this might be a silly question, but basically for the project I'm building currently, the UI has been developed on React Native, and I'm coding the backend on Django. I haven't integrated the frontend and backend yet. So basically, how do I check if my Django backend code is working without integration? -
MultiValueDictKeyError at /rapport
any solutions in this django problem ? im trying to display hex2 and it marked that 'data' is a multivaluedictkeyerror . but in my console the code works normally and print the result without problemes i need to figure how to solve this display probleme thank you views.py def search(request): context = {} hex1="" hex2="" if request.method == 'POST': hex2, hex1 = request.POST['data'].split("+") print(hex2,hex1) context['hex2']=hex2 return render(request,"p33/rapport.html",context) photo rapport.html <table class="table"> <tbody> <tr> {%for hex in hex2.items%} {% csrf_token %} <tr class="table-row"> <td>{{hex}}</td></tr> {%endfor%} </tr> </tbody> </table> </div> urls.py path('rapport',views.search,name="rapport"), -
How to add Product details logic like amazon in an ecommerce website using Django
I am trying to build an e-commerce website using Django but I am not able to figure out how companies like Amazon and Flipkart store product details like this. I can hardcore this thing by making each attribute in the database but I think it is not the most efficient way to do this. There gonna some other way to do the same thing so please give me some valuable suggestions -
How to check the filter object is returning any data or not django
I have a model named Rooms. Now I want to check if a specific row exists in the model or not by this line of code: checkroom = Rooms.objects.filter(building_id=building_id, room_no=room_no).first() If the row doesn't exist, then I want to print some text: How Can I check the condition? I have used if checkroom: this condition to check if it exists. but now I want to check if it doesn't exist separately. -
Django-cors-headers not working though all the configuration seems correct
I tried many ways configuring the django-cors-headers But unfortunately it is not working for me even after meeting the requirements for the package as. Django Version - 3.2.13 Python Version - 3.7/3.10 (Tried both) I have the following configuring in my settings.py INSTALLED_APPS = [ 'employee.apps.EmployeeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] And even tried setting the config to CORS_ALLOW_ALL_ORIGINS = True Even trying after all of these configurations I was not able to make it work. Please help me with this issue. -
Why is Django setting default values to all existing model attributes?
I have a model called Book. Book has the following attributes: title, release_date and condition where condition has a default value set to "new". I created some of Books in django admin site. After I created a new attribute for this model called category which it has a default value set to Non-fiction. Why is django setting category = "new" to all existing books instead of "Non-fiction". With the books that I add after the migration Django set them correctly. Why is this happening. class Book(models.Model): class ConditionType(models.TextChoices): USED = "Used" NEW = "New" class Category(models.TextChoices): ACTION_ADVENTURE = "Action and Adventure" CLASSIC = "Classic" MYSTERY = "Mystery" FANTASY = "Fantasy" HORROR = "Horror" LITERERY_FICTION = "Literary Fiction" SCIENCE_FICTION = "Science Fiction" NON_FICTION = "Non-Fiction" NO_CAT = "No category" title = models.CharField( max_length=150, null=False, ) release_date = models.DateField() condition = models.CharField( max_length=12, choices=ConditionType.choices, default=ConditionType.NEW, ) category = models.CharField( max_length=40, choices=Category.choices, default=Category.NO_CAT, ) After the first migration I added the category field btw. -
instance is not popping from validated_data
I am building a simple blog app and I am trying to save two models with one of them ForeignKey with other, so I was trying to save both records so I tried to use validated_data.pop But it showed Got AttributeError when attempting to get a value for field images on serializer BlogSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'images'. But I have checked the response by printing like :- print(validated_data) It is successfully showing { 'images': [ OrderedDict([('image_text', 'First Image'), ('blog', <Blog: First Blog>)])], 'blog_title': 'First Blog', 'owner': <User: user_1> } As you can see, It is showing images in validated_data But it is not working when I use pop models.py class Blog(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) blog_title = models.CharField(max_length=100) class Image(models.Model): blog = models.ForeignKey(Blog, related_name='blog', on_delete=models.CASCADE) image_text = models.CharField(max_length=100) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class BlogSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Blog fields = "__all__" def create(self, validated_data): images = validated_data.pop("images") return validated_data I have tried many times but it is still showing the same Any suggestions would be … -
Django get_language_info_list in template is empty
I am making a website where the user can decide to view the website in either English or Dutch. I would like to do this with a dropdown menu, and for this I have added the following: settings.py: from django.utils.translation import gettext_lazy as _ MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'snvs/locale/' ] LANGUAGES = ( ('en', _('English')), ('nl', _('Nederlands')) ) urls.py (main one) urlpatterns = i18n_patterns( path('', views.home, name='home'), path('i18n/', include('django.conf.urls.i18n')), path(_('admin') + '/', admin.site.urls, name='admin'), path(_('agenda') + '/', include('agenda.urls'), name='agenda'), path(_('winkel') + '/', include('store.urls'), name='store'), ) my base template: {% load i18n %} ... {% get_language_info_list for LANGUAGES as languages %} {% if languages|length > 1 %} <form action="{% url "set_language" %}" method="post" class="d-flex"> {% csrf_token %} <select name="language" class="form-select" onchange="this.form.submit()"> {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}> {{ language.name_local }} </option> {% endfor %} </select> </form> {% endif %} However the LANGUAGES, languages or get_language_info_list tag in the template always is an empty list, whereas it should return the LANGUAGES information as described in settings.py (documentation) … -
Django Middleware object is not callable
I'm trying to write custom middleware for catching exceptions and returning the proper HTTP Response object. But for some reason, I'm getting a "middleware object is not callable" error. I'm raising an exception in view layer like below class MyView(APIView): def post(self, request): result = some_func(request) #this func raises an exception return Response({"status": "Success", "data": result}) logs. backend_1 | INFO:django:BEGIN -> c25db666-e89c-43a5-9f28-48001e301829 - /myapp/settings/create backend_1 | {"message": "Internal Server Error: /myapp/settings/create", "exc_info": "Traceback (most recent call last):\n File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 47, in inner\n response = get_response(request)\nTypeError: 'MyAppResponseMiddleware' object is not callable", "status_code": 500, "request": "<WSGIRequest: POST '/myapp/settings/create'>"} backend_1 | ERROR:django.request:Internal Server Error: /crystal/settings/create backend_1 | Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner backend_1 | response = get_response(request) backend_1 | TypeError: 'MyAppResponseMiddleware' object is not callable files #myapp/middleware.py class MyAppResponseMiddleware: def __init__(self, get_response): self.get_response = get_response def process_exception(self, request, exception): absolute_path = request.get_full_path() print(absolute_path) print(exception.__class__.name) print(exception.message) #settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", ... ... <some custom middleware> ... "myapp.middleware.MyAppResponseMiddleware", ] I've added middleware in the last so that my middleware catches the response/exception before other middleware process the response. -
How to format timzone.now() in Django in models.py?
I have a DateField in my models.py, which is set to timezone.now(). How can I change the date format that it is saved in? I appreciate that I can change it in the template easily enough, but this won't solve my particular problem. I have tried adding the below into my settings.py, but nothing has changed. USE_L1ON = True DATETIME_INPUT_FORMATS = ('d-m-Y') I would be very grateful for any help here. -
Turbolinks + Django: Page is requested multiple times when the "prevoius" button is pressed in the browser
I have finally got Turbolinks to work fine and dandy and handle all of the requests going through my application (PJAX). However, the main issue that arises is the fact that the "back/previous" button is broken. The normal page request when normally navigating through a turbolink should be as follows: Normal Network activity However, when pressing on the "previous" button all hell gets loose as follows: When clicking the previous button in the browser The page named "11" should load one time only. However, it loads multiple times for some reason. I know turbolinks is famous with the Rails framework so any answers are welcome. Also, I'm inexperienced with how caching works with Turbolinks, so if this is a cache issue please refer me on how to mitigate it. -
Form data is not transferring from views.py to html table in Django
I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API and it's working too. But I am facing an issue in transferring back the form data in the HTML table. It's not going back to the table at all. Without the fetch API form submission, the data are getting transferred back to the HTML table as it's supposed to. But I am not able to do the same after implementing fetch API in my app. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST.get['dropdown_val'] value=request.POST.get['val'] print(options_value,value) context={"options_value":options_value, "value" : value} return render(request, 'index.html',context) **index.html" <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" … -
how to pass file from local storage to html - django
so i want get my file from local storage to show in html using django. but i don't know how to get it. the file is audio mp3. i was using form NOT MODALS. i need reference of example code. if you need my code form.py here's : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) i was try using formset, but i don't know how to use it. here's my views.py code : def song(request): songmp3 = formset_factory(Audio_store) if request.method == 'POST': formset = songmp3(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = songmp3() return render(request, 'homepage.html', {'formset': formset}) -
How do I make text "bold" in email body in python?
How can I make text bold in the email body in python? I am using the following code to send mail : from django.core.mail import send_mail send_mail(subject, message, sender, [email], fail_silently=False) I want to make some important text bold. Using the following code I have received the whole string as a message. message = " Hi Customer,<br> Your OTP is <b>****</b>" But it works when I try \n as <br>. What can I do to make the text bold? -
Custom form in Django shows ids instead of string
guys! I'm struggling with django forms. Default ones represent models as expected (returning __ str __ values). However, my custom form (Event_form_for_Admin) shows ids instead of string in admin panel and on the site. What am I missing? models.py class Position(models.Model): name = models.CharField(max_length=800) level = models.CharField(max_length=50) def __str__(self) -> str: return f'{self.level} {self.name}' class Person(models.Model): name = models.CharField(max_length=300) def __str__(self) -> str: return self.name class Event(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) position = models.ForeignKey(Position, on_delete=models.RESTRICT) def __str__(self) -> str: return f'{self.action} {self.position}' forms.py class Event_form_for_Admin(forms.ModelForm): person = forms.CharField(widget=forms.TextInput, label='Name') position = forms.CharField(widget=forms.TextInput, label='Position') class Meta: model = Event fields = ['person','position'] output on site as well as in admin panel: -
Allow all ips in CSRF_TRUSTED_ORIGIN django
How to allows all/ any ips in CSRF_TRUSTED_ORIGIN of django Backend django restapi are running and frontend is on angular in one system and we are trying to access with system ip in another system, i am able to access frontend and while accessing backend POST method API's are not working it's showing not found in card trusted origins. In settings.py i made get dynamic ips. import socket def get_ipaddress(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) return "http://"+ip_address+":4200" ALLOWED_HOSTS=["*"] CSRF_TRUSTED_ORIGINS=[get_ipaddress()] Tried to use csrf_excempt , but it's not working. Version of django4.0.1, Angular 16 -
How do I access image URL from one django model to another? How do I put it on a template?
I am using two models Forum and User. User model.py: class User(models.Model): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) profile_img = models.ImageField(upload_to='images/', null=True, blank=True) I wanted to access the url of User's profile_img and display it to my template in Forum. How should I code this in my Forum's model.py? -
Cannot populate elasticsearch index using ```python manage.py search_index --rebuild``` in django using docker
I am using django, elasticsearch and postgresql from docker in separate containers. When I try to run python manage.py search_index --rebuild, I get the following error: Traceback (most recent call last): File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 22, in <module> main() File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 166, in handle self._rebuild(models, options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 143, in _rebuild if not self._delete(models, options): File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 132, in _delete "the '{}' indexes? [y/N]: ".format(", ".join(index_names))) TypeError: sequence item 0: expected str instance, NoneType found Everything else works fine. When I run docker-compose up, all of my containers i.e. the postgresql database, web service and the elasticsearch containers start running without any problems. The website starts running on localhost:8000 and I can also create new users from the admin panel. So, the website and database are working fine. On localhost:9200, I can see the following JSON: { "name" : "4336b15c63fa", "cluster_name" : "docker-cluster", "cluster_uuid" : "a_long_string", "version" : { "number" : "7.14.2", "build_flavor" : "default", "build_type" : "docker", "build_hash" … -
'Access is denied' on wrong port select
could not open port 'COM#': PermissionError(13, 'Access is denied.', None, 5) actually this is not a mistake, I want to show window alert message when someone select wrong port if anyone knows please help def add_charger_view(request): if request.method == 'POST': port = request.POST['port'] port = port.split().pop(0) baud_rate = request.POST['baud_rate'] serial.Serial(port, baud_rate) return render(request, "charger.html", context) all things good, connection is ok but shows this error in not ok -
user registered but cannot login django
I tried to implement customized user login/ Registration in django. but only one user can be logged in but not anyother user are logged in. Registration area looks fine cause user can register easily. These are my codes I guess there is problem with CSRF token but i dont know where to update it In view Register def registerPage(request): form = UserForm() if request.method == 'POST': print(request.POST) form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.user_name = user.user_name.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'An error occured duing registration!!') return render(request, 'base/login_register.html', {'form': form}) My Views Login def loginPage(request): page = "login" if request.user.is_authenticated: return redirect('home') if request.method == "POST": email = request.POST.get('email').lower() password = request.POST.get('password') try: user = NewUser.objects.get(email=email) except: messages.error(request, 'User doesnot exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) print("mess going on here!") return redirect("home") else: messages.error(request, "Email or Password doesnot exit") context = {'page': page} return render(request, 'base/login_register.html', context) Forms.py from tkinter import Widget from django.forms import ModelForm from .models import NewUser class UserForm(ModelForm): class Meta: model = NewUser fields=['email','user_name','first_name','country','address','year_in_school','about','avatar'] def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'class': 'form-control'}) # self.fields['email','user_name','first_name','country','address','year_in_school','about'].widget.attrs.update({'class': 'form-control'}) self.fields['user_name'].widget.attrs.update({'class': 'form-control'}) self.fields['first_name'].widget.attrs.update({'class': 'form-control'}) self.fields['country'].widget.attrs.update({'class': 'form-control'}) self.fields['address'].widget.attrs.update({'class': 'form-control'}) … -
The directory 'D:\dj\staticfiles' in the STATICFILES_DIRS setting does not exist
This is my settings.py I already created a folder 'staticfiles' in the project folder. How can I solve the error -
'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)])
I am building a simple gallery image app and using django-rest-framework. I am saving two model instances, which I am rendering as nested response and also saving throughh nested json. But when I click on Post from api admin then it is showing 'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]) I think the problem is in the create() function. I have also tried modifying it but it is still not working and showing the same error. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): created = Gallery.objects.create(poll=1) created.images.set(validated_data['images']) return created my response which I am saving { title: "First Gallery", images : [ { "gallery": 1, "text": "First Image" } ] } And When i print validated_data like :-: print(validated_data['images']) then it is showing [OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Second Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Third Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Fourth Image'), ('gallery', <Gallery: First Gallery>)])] I have just started learning …