Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a extra field to user (create user including that field)
I want to use an extra field let me distinguish between user roles. For that, I've overriden the User class: class User(AbstractUser): role = models.CharField(max_length=21, blank=False) I've also put this in settings.py: AUTH_USER_MODEL = 'shopping.User' The problem is that I have the new field in my database, but, if I want to create a new user using the admin, it doesn't ask me for the role. I suppose that I have to override the save method too, but I don't know how. Thanks in advance -
Any suggestions on how to improve programming ability without actually coding?
My background is web development for around a year using Django and react. In the following year, I have to go out for 2 weeks per month, without being around a pc. Anyone has an idea about how to overcome this obstacle and improve my skills? -
Getting model data associated with a username and displaying it in HTML in Django
I have a model that associates points and donations with a user. In my view, I want to get the data for the user who is currently logged in and display his donations and points in HTML. How would I go about doing this? The model, view, and HTML are down below. View (I want to get the points and donations assosicated with the user currently logged in).: @login_required(login_url='/login/') def dashboard(request): return render(request,'dashboard.html', ) Model: class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML (Instead of a 0, I want to display the points, and the same for the donations): <div class="box"> <span class="value">0</span> <span class="parameter">Points</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> Thank you to everyone who helps! -
Recover XMLHttpRequest() with django
I'm trying to do an XMLHttpRequest() with js and recover the data with django and I received None but in the js code the status is 200 and the info is returned. How can I fix that to use the data send with the XMLHttpRequest()? js code: var xhttp = new XMLHttpRequest(); var data = JSON.parse('{"startdate":'+start_Date+'}') console.log(data) xhttp.open("GET", "/scoStart/", true); xhttp.send(data); xhttp.onreadystatechange = function () { if (xhttp.readyState == 4 && xhttp.status == 200) { try { var obj = JSON.parse(xhttp.responseText); console.log(obj) } catch (error) { throw Error; } } } Django code: def scoStart(request): user_id = request.session.get('idnickname') startdate = request.GET.get("startdate") return HttpResponse(json.dumps({str(user_id):user_id}),'application/json') -
GEOSException while try to add a new object to database in django - geoDjango
-> whenever i try to add a new estate a GEOexception error pops up I don't know if its because the configuration of gdal, idk If m doing something wrong. model.py: class Estate(models.Model): """model the estates class which will control the estates management aspect """ Es_label = models.CharField(max_length=20, unique=True, null=False) Es_description = models.TextField(max_length=200, unique=True, null=False) Es_surface = models.FloatField(null=False) Es_characteristics = JSONField(blank=True, null=True) Es_equipment = JSONField(blank=True, null=True) Es_geoLocation = PointField() objects = Manager() Es_sold = models.BooleanField(default=False) slug = models.SlugField(max_length=200, unique=True, default="SlugX") # define foreign keys for estates tables Es_project = models.ForeignKey( Project, on_delete=models.CASCADE, null=False) Es_status = models.ForeignKey(Status, on_delete=models.CASCADE, null=False) Es_Type = models.ForeignKey(Type, on_delete=models.CASCADE, null=False) i configure gdal to be accessed within my venv called Genv settings.py #setting up path for gdal to be used from within the env import os if os.name == 'nt': VENV_BASE = os.environ['VIRTUAL_ENV'] os.environ['PATH'] = os.path.join(VENV_BASE,'lib\\site-packages\\osgeo') + ';' + os.environ['PATH'] os.environ['PROJ_LIB'] = os.path.join(VENV_BASE,'lib\\site-packages\\osgeo\\data\\proj') + ';' + os.environ['PATH'] #GDAL_LIBRARY_PATH = 'D:\Final_Studies_Project\Genv\lib\site-packages\osgeo\gdal303.dl l' admin.py from django.contrib import admin from django.contrib.gis.admin import OSMGeoAdmin # Register your models here. from .models import * admin.site.register(Project) admin.site.register(Type) admin.site.register(Media) admin.site.register(NewsLetter) admin.site.register(Status) @admin.register(Estate) class MarkerEstateAdmin(OSMGeoAdmin): """Marker admin.""" list_display = ("Es_label", "Es_geoLocation") -
HttpOnlyCookie not being set after I added domain to my website
I'm trying to upload my first website which consists of frontend(react) and backend(django). So when I use it on development, all works just fine, it also works fine when I search for the IP of my VPS, but the problem comes when I try to login with the domain instead of the ip, for some reason the cookie isn't set after I login, but in with the IP it does, fyi both of them use the exact same backend and frontend. Here is the web: website with domain and here is the one without domain/IP website without domain -
QuerySet' object has no attribute 'posts'
Am having a challenge to get users post on their timeline and I would appreciate if anyone could help me. I keep coming against this error(QuerySet' object has no attribute 'posts') when ever filter through the post object. I wonder what am missing out on here ? here is my model for post. class Post(models.Model): description = models.CharField(max_length=5000, blank=True) pic = models.ImageField(upload_to='path/post/img' ,blank=True) date_posted = models.DateTimeField(auto_now_add=True) user_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users") tags = models.CharField(max_length=100, blank=True) here is my view for users account since i want every user to have their post on their timeline. def account_view(request, *args, **kwargs): """ - Logic here is kind of tricky is_self is_friend -1: NO_REQUEST_SENT 0: THEM_SENT_TO_YOU 1: YOU_SENT_TO_THEM """ context = {} user_id = kwargs.get("user_id") try: account = User.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['bio'] = account.bio context['get_full_name'] = account.get_full_name context['email'] = account.email context['profile_pic'] = account.profile_pic.url context['cover_image'] = account.cover_image.url context['city'] = account.city context['country'] = account.country context['gender'] = account.gender context['hide_email'] = account.hide_email try: post_list = Post.objects.filter(user_name=account) except Post.DoesNotExist: post_list = Post(user_name=account) save.post_list() posts = post_list.posts.all() context['posts'] = posts try: friend_list = FriendList.objects.get(user=account) except FriendList.DoesNotExist: friend_list = FriendList(user=account) friend_list.save() friends = friend_list.friends.all() context['friends'] = … -
Django - storing session object in settings.py
I have an api(legacy), a front end app(legacy) , and a django app(in development). Both the legacy front end app is fully working with the legacy api that operates with a mysql database. I have integrated my django app with that database and for some features I am using some endpoints from the legacy api. In order to do that I must login by sending credentials to that api - I am doing this using python sessions in order to store the cookie. Question Is it safe to instantiate the session object in the settings.py? from requests import Session session = Session() Is there a better way to communicate with the legacy api? Maybe using django sessions as cookie, I have tried many ways to make it work and it works now. If I am using a cookie with JSESSIONID=random string then api does not accept that as a cookie. That's why I am using python sessions. -
Trouble deploying django webapp onto google cloud
I've been following the google cloud documentation titled, "Running Django on the App Engine standard environment" . I'm using the same app provided in the documentation in the "Cloning the Django App". Honestly, I get lost in the google cloud documentation under the "Configuring Database Settings" section. This what my settings.py (mysite/settings.py in the given app mentioned previously) Mysite/settings.py img Whenever running python manage.py makemigrations - I get the following error message on the CLI... django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable Also, I have noticed there is no .env file in that repo. Would I maybe have to create it myself or would is it fine? Again I am using the github given app via the documentation. Just trying to deploy Django website to google cloud. Any help would be greatly appreciated. Im on Mac Big Sur btw if that matters. -
FastCGI , Django e Apache
My server is share. I use apache2, django1.11 and python2.7 So, for run the applications only FastCGI. It's run website, but error this command python index.fcgi >>>>.htaccess AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] >>>>>index.fcgi #!/usr/bin/scl enable python27 -- /home/user/venv/bin/python import os import sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert(0, "/home/user/project/borracharia") os.environ['DJANGO_SETTINGS_MODULE'] = "borracharia.settings" WSGIServer(get_wsgi_application()).run() ~ ~ (venv)user@site.com[www]# python index.fcgi WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Status: 400 Bad Request Content-Type: text/html I want to help this problem? -
Dockerfile, docker-compose.yml and Postgresql configuration "password authentication failed"
Contents of Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r requirements.txt Contents of docker-compose.yml version: "3.9" services: db: image: postgres container_name: postgresdb environment: - POSTGRES_DB=db - POSTGRES_USER=user1 - POSTGRES_PASSWORD=password - POSTGRES_HOST_AUTH_METHOD=trust volumes: - pgdb-data:/var/lib/postgresql/data levelupworks: build: . environment: - DB_NAME=levelworks - DB_USER=user1 - DB_PASS=password - DB_HOST=db command: > bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code image: levelupworks-image container_name: levelupworks-app ports: - "10555:8000" depends_on: - db volumes: pgdb-data: driver: local Contents of settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'HOST': os.environ.get('DB_HOST'), } } Output of: "docker logs levelupworks-app" /usr/local/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': FATAL: password authentication failed for user "user1" warnings.warn( No changes detected Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) … -
OrderForm has no attribute 'as_widget' error during update the values
I have a function for update the table data. Once I click on update, it shows me the above error. Here are my codes. views.py def updateOrder(request, pk): action = 'update' order = Order.objects.get(id=pk) form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('order-list') else: form = OrderForm() context = {'action': action, 'form': form} return render(request, 'store/update_order.html', context) HTML {% load widget_tweaks %} <form action="" method="POST"> {% csrf_token %} {% for field in form %} {{field.label}} {{field|add_class:'form-control'}} {% endfor %} <hr> <input type="submit" class="btn btn-info"> </form> Any idea how to solve this? For more information, this is how I create an order https://gist.github.com/TaufiqurRahman45/269410a6d951516cdcf6939652a43739 -
Prevent Django LDAP plugin from creating user in DB
I want to limit the users stored in the DB to superusers, staff, and users with special permissions, but I don't want info from "normal" users to be stored in the DB when they login with their LDAP credentials. Is there a way to do this? -
How to download .apk by user URL and take metadata from it by python
I need by user URL download the application only for metadata. After it can be deleted. URL need to be direct link, so if you go through it, download starts immediately. So how I can do it by python(django)? -
i'm having Django page not found error, 404 Error
please, somebody should explain what is wrong with the code. [1]Link to the code: https://github.com/ijawpikin/projectHub.git [2]: https://i.stack.imgur.com/rryPP.jpg -
How can I rebuild search index of Elasticsearch in Django automatically on docker startup?
It's my first time using Elasticsearch with Django on Docker and I realize that every time I start docker-compose, I have to issue ./manage.py search_index --rebuild to index all my documents in Elasticsearch. I've been trying to do this automatically but still doesn't seem to work. My web service command looks like this: web: build: . command: bash -c "python manage.py runserver 0.0.0.0:8000 && sleep 60 && python manage.py search_index --rebuild" ... I added sleep 60 so that it can wait for Elasticsearch to start up before issuing the rebuild command. And even with that, nothing happens unless I explicitly issue it manually. -
Receiving a no such column error in Django
I'm attempting to make individual pages for toppings in a pizza, and I received a no such column error and i'm not sure what's going on. Doing an exercise from the Python Crash Course 2nd Ed (Ch.18, Ex.8), I've tried applying migrations, I'm able to go through the pages of index and pizzas, but unable to enter the pages of each pizza which displays toppings on them, sorry if I posted any unimportant code. models.py from django.db import models # Create your models here. class Topping(models.Model): """A pizza topping""" topping = models.CharField(max_length=30) def __str__(self): """Return a string representation of the topping.""" return self.topping class Pizza(models.Model): """A pizza type""" name = models.CharField(max_length=30) toppings = models.ManyToManyField(Topping, blank=True) def __str__(self): """Return a string representation of the pizza type""" return self.name urls.py """Defines URL patterns for pizzas""" from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ #Home page path('', views.index, name='index'), #Page that shows all the pizzas. path('pizzas/', views.pizzas, name='pizzas'), #Detail page for a single topic. path('pizza/<int:pizza_id>/', views.pizza, name='pizza'), ] views.py from django.shortcuts import render from .models import Pizza # Create your views here. def index(request): """The home page for pizzas.""" return render(request, 'pizzas/index.html') def pizzas(request): """Show all the … -
Django image not found using pillow deployed on heroku
Hello I get this error on my picture that I uploaded to the website that was hosted on heroku the error Page not found (404) “/app/media/Thumbnail/WhatsApp_Image_2021-05-22_at_1.58.10_PM_sixTZxy.jpeg” does not exist Request Method: GET Request URL: https://dpmission.herokuapp.com/media/Thumbnail/WhatsApp_Image_2021-05-22_at_1.58.10_PM_sixTZxy.jpeg Raised by: django.views.static.serve Using the URLconf defined in DPM.urls, Django tried these URL patterns, in this order: [name='home'] front [name='front'] ytvideos [name='ytvideos'] Reading [name='reading'] KGK [name='KGK'] viewKGK/<str:pk> [name='viewKGK'] viewreading/<str:pk> [name='viewreading'] admin/ ^media/(?P<path>.*)$ The current path, media/Thumbnail/WhatsApp_Image_2021-05-22_at_1.58.10_PM_sixTZxy.jpeg, matched the last one. My code works perfectly fine because before this all the images can be view on the website only a few days ago the image become img cap top, I dont know what is the problem and when I use local server using python manage.py runserver the image still can be see This is my setting.py """ Django settings for DPM project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os.path from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep … -
How to limit the number of items of a ForeignKey field when I'm fetching an object in Django GraphQL API using Graphene?
I have a simple chat application with a GraphQL API written in Django with Graphene plugin. And an Angular UI with Apollo as the GraphQL client. I have a chat model that is like chat rooms and a chatMessage model that is more of the individual message that is tied to the chat model via a foreignKey field, so that every chat message is tied to some chat item. The following is the model specification in Django:- class Chat(models.Model): name = models.CharField(max_length=100, blank=True, null=True) admins = models.ManyToManyField(User, related_name="adminInChats", through="ChatAdmin", through_fields=( 'chat', 'admin'), blank=True) members = models.ManyToManyField(User, related_name="privateChats", through="ChatMember", through_fields=('chat', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class ChatAdmin(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.chat class ChatMember(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.chat class ChatMessage(models.Model): chat = models.ForeignKey(Chat, on_delete=models.PROTECT) message = models.CharField(max_length=1000) author = models.ForeignKey( User, related_name="chatAuthor", on_delete=models.DO_NOTHING) seenBy = models.ForeignKey( User, related_name="chatSeenBy", on_delete=models.PROTECT, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.chat And I'm using GraphQL to fetch an individual chat item. The following is the backend code for it:- class Query(ObjectType): chat = graphene.Field(ChatType, id=graphene.ID()) @login_required … -
custom manager for base models.Model
Let's say I have the following classes: class BaseHistorizationModel(models.Model): value = models.DecimalField(decimal_places=2, max_digits=5) date_begin = models.DateField(db_index=True, blank=True, null=True) date_end = models.DateField(db_index=True, blank=True, null=True) class Meta: abstract = True ordering = [F("date_begin").desc(nulls_last=True)] class NbOccupant(BaseHistorizationModel): value = models.IntegerField() building = models.ForeignKey( Building, on_delete=models.CASCADE, related_name="nb_occupants", ) class Temperature(BaseHistorizationModel): value = models.IntegerField() city = models.ForeignKey( City, on_delete=models.CASCADE, related_name="nb_occupants", ) I would like to implement some class methods such as get_mean_value in BaseHistorization but for NbOccuppant I need to filter objects with building and for Temperature I need to filter with city. I think I need to do something like the following: mean_nb_occupant = NbOccupant.get_mean_value(start, end, building=building) mean_temperature = Temperature.get_mean_value(start, end, city=city) ... class BaseHistorization(models.Model): ... @classmethod def get_mean_value(cls, date_begin, date_end, **extra_kwargs): pass But I don't find a clean way to overide all my calls to cls.objects.filter or cls.objects.get inside BaseHistorization. I think CustomManager could help me but I do not exactly see how. -
Unsupported lookup 'search' for django.core.exceptions.FieldError
I'm trying to do a full text search on my postgres db witn Django ORM like this: Model.objects(column__search='value') Unfortunately, this query results with this error: django.core.exceptions.FieldError: Unsupported lookup 'search' for TextField or join on the field not permitted. How to fix that? -
Add users on local db on user creation in firebase python django
I have been using the django default auth backend for my authentication.Recently I decided to use firebase for my authentication while maintaining my users in my postgres db. I have used Pyrebase to do user creation and sign in on firebase from my django backend.This works well.But now I need to create the users on my local db as they get created on firebase, since I do not want to have two different sets of users on firebase and on my db .What is the best way to achieve this or can someone point me in the right direction? Views.py "apiKey": "AIzaSyBAfh2M6EOkXfRXBT1BVMxIET6iQzCOn1Y", "authDomain": "finance-web-auth.firebaseapp.com", "databaseURL": "https://finance-web-auth-default-rtdb.firebaseio.com", "storageBucket": "finance-web-auth.appspot.com", } firebase = pyrebase.initialize_app(config) auth = firebase.auth() class AuthCreate(APIView): permission_classes = [AllowAny] def post(self, request, format=None): email = request.POST.get("email") password = request.POST.get("password") user = auth.create_user_with_email_and_password(email, password) auth.send_email_verification(user['idToken']) return Response(user) This is the response I get once a user gets created "kind": "identitytoolkit#SignupNewUserResponse", "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg4ZGYxMz", "email": "siderra@poneahealth.com", "refreshToken": "AGEha4v_rqVydtffrhjizMtqkQaOJz5_gW4aAb9J-xqY6WL_tDMBX_kQA", "expiresIn": "3600", "localId": "vasavF3" } -
passenger_wsgi.py modification to run a Django application
I wrote a Django test application, it works in my local Django server but it does not run on the shared web server based on Passenger (ifastnet.com). This is my original passenger_wsgi.py file: #--------------------------------------------------------------------------- # \file passenger_wsgi.py # \brief # # \version rel. 1.0 # \date Created on 2021-05-24 # \author massimo # Copyright (C) 2021 Massimo Manca - AIoTech #--------------------------------------------------------------------------- import os import sys sys.path.insert(0, os.path.dirname(__file__)) def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) message = 'It works!\n' version = 'Python %s\n' % sys.version.split()[0] response = '\n'.join([message, version]) return [response.encode()] #--------------------------------------------------------------------------- and this is my passenger_wsgi file modified to run my application: #--------------------------------------------------------------------------- # \file passenger_wsgi.py # \brief # # \version rel. 1.0 # \date Created on 2021-05-24 # \author massimo # Copyright (C) 2021 Massimo Manca - AIoTech #--------------------------------------------------------------------------- import os import sys sys.path.append(os.path.dirname(__file__)) os.environ['DJANGO_SETTINGS_MODULE'] = 'DjHelloWorld.settings' from DjHelloWorld.wsgi import application the first works the second does not. DjHelloWorld.wsgi.py: """ WSGI config for DjHelloWorld project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjHelloWorld.settings') application = get_wsgi_application() DjHelloWorld.settings.py """ Django settings for DjHelloWorld project. Generated by 'django-admin startproject' using Django … -
How can I check if a charfield result is something specific?
I want to check if Category in this method is Toys. Here is the method: class Product(models.Model): CATS = ( ("T", "Toys"), ("C", "Clothes"), ("B", "Baby essentials") ) Title= models.CharField(max_length=100) Description= models.TextField() Colours= models.CharField(max_length=200) Category=models.CharField(max_length=1, choices=CATS) Price=models.IntegerField(default=1) image_one = models.ImageField(upload_to='media', default='def.jpg') image_two = models.ImageField(upload_to='media', default='def.jpg') image_three = models.ImageField(upload_to='media', default='def.jpg') What I did in the HTML template: {% extends "ecomm/base.html" %} {% block content %} {% for p in products%} {% if p.Category==Toys %} <p> {{p.Title}}</p> <p> {{p.Price}}</p> <p> {{p.Description}}</p> {% endif %} {% endfor %} {% endblock %} -
Django double nested serializer
I am writing an api's application where Order is an entity that provides information about what customers want to buy, one Order can contain different products with different quantity and different prices. The entity that includes this information in Order is called Order Detail. And I have some problems with double nested serializers. After post request with: { "external_id": "PR-123-321-123", "details": [{ "product": {"id": 4}, "amount": 10, "price": "12.00" }] } I want to get this response: { "id": 1, "status": "new", "created_at": "2021-01-01T00:00:00", "external_id": "PR-123-321-123", "details": [{ "id": 1, "product": {"id": 4, "name": "Dropbox"}, "amount": 10, "price": "12.00" }] } But now i have some error: "Cannot assign "OrderedDict()": "OrderDetail.product" must be a "Product" instance." What's wrong? Models: from django.db import models class Order(models.Model): STATUS_CHOICES = ( ('new', 'new'), ('accepted', 'accepted'), ('failed', 'failed') ) status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='new') created_at = models.DateTimeField(auto_now_add=True) external_id = models.CharField(max_length=128, unique=True) class Product(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class OrderDetail(models.Model): order = models.ForeignKey(Order, related_name='details', on_delete=models.CASCADE) amount = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return f'{self.order} detail' Serializers: from rest_framework import serializers from rest_framework.serializers import ModelSerializer from order.models import Order, Product, OrderDetail class ProductSerializer(ModelSerializer): class Meta: model = …