Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GraphQL add json from related table as field in GraphQL query
I have a few tables - magic_sets, magic_sets_cards, magic_sets_tokens, magic_setssealed_products - the latter three tables all have foreign keys to a specific record in magic_sets table. I am trying to create a GraphQL schema to bring back a specific set along with its related cards, tokens and sealed_products. I have it so it brings back a specific set but the cards field is returning a error code: class MagicSetsIndividual(DjangoObjectType): cards = GenericScalar() class Meta: model = magic_sets fields = ['id', 'code', 'keyrune_code', 'release_date', 'non_foil_only', 'foil_only', 'digital', 'cards'] def resolve_cards(self, info, **kwargs): return magic_sets_cards.objects.filter(set_id=self).all() class MagicSetsIndividualQuery(graphene.ObjectType): magic_sets_individual_cards = graphene.List(MagicSetsIndividual, code=graphene.String()) def resolve_magic_sets_individual_cards(self, info, code=None, **kwargs): return magic_sets.objects.filter(code=code).all() query: { magicSetsIndividualCards(code: "SS1") { id code keyruneCode releaseDate nonFoilOnly foilOnly digital cards } } error: TypeError at /magic/api/v1/sets/individual/cards/\nObject of type QuerySet is not JSON serializable\n\nRequest Method: -
Django channels crashes whenever made a database call
I have this code and I am making a database call in the connect method. The code runs fine if I comment the database call async def connect(self): pk: int = self.scope['url_route']['kwargs']['pk'] params: str = self.scope['query_string'].decode("utf-8") email: str = params.split('=')[1] # self.project: Project = await self.get_project(pk) self.room_name = "Room name!" self.room_group_name = 'chat_%s' % pk await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() @database_sync_to_async def get_project(self, pk: int) -> Project: return Project.objects.filter(id=pk).first() Can someone help me with this ? Thanks in advance -
Get data from another table foreign key python
I have two tables called User and Duty. The common value in these two tables is account_id (for User) and ID (for Duty) I would like to get another value in table Duty called work_id. Should I use prefetch_related? User uid name last_name state account_id 1ldwd John Black active 123 2fcsc Drake Bell disabled 456 3gscsc Pep Guardiola active 789 4vdded Steve Salt disabled 012 Table Duty uid rate hobbie id work_id 1sdeed part football 456 007 3rdfd full hockey 789 022 45ffdf full regbie 123 4567 455ggg part fishing 012 332 -
django token authentication access the logged in user
how do i know a user is authenticated when i use token authentication?....i have tried accessing request.user and auth but it outputs anonymousUser.....when i set the authentication class to TokenAuthentication and permission class to isAuthenticated,and the URL endpoints as restframework.urls,i get a 401 "Authentication credentials were not provided" exception.....when i remove the TokenAuthentication settings,the app works perfectly....in short,i want to access the user logged in when i use token authentication method...thanks alot -
How get user's input from html form, and use it in my function in Django app
How do I get the user's input, and use it in my Python function? This button creates a PDF document. I need the name that the user enters to be added to this pdf file. -
: AttributeError: 'str' object has no attribute 'resolve' o
I am new to django i am using a mac os system , i am trying to do a simple hello world program in django framework The initial set up and launching works fine , but while creating a helloworld program by creating a new app and deploying it i am getting below error can some one help how to resolve this issue. **Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/Users/ushanandhini/Desktop/djngo/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/ushanandhini/Desktop/djngo/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ushanandhini/Desktop/djngo/hello/views.py", line 8, in home return HTTPResponse("hello Nikhil") File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/http/client.py", line 256, in __init__ self.fp = sock.makefile("rb") Exception Type: AttributeError at / Exception Value: 'str' object has no attribute 'makefile' Thanks, Sid** -
Django testing models.py file
I am performing the Django for my models.py file Here is my models.py file import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) farm_health … -
How to import .py file from django's static dir from within a brython.html template?
Like the title says, I'm running a django webapp using Brython (NOT Javascript), hosted on Heroku, and would like to import a .py file located in the static folder. I am able to import and display the contents of the .py file, but when I try to import it, the webpage remains blank (white screen) with no errors (status 200). My debugging is possibly not developed enough to catch the error, but usually I will get a traceback when I have errors as debugging is on. So, the status 200 and blank white screen are important, I believe. Although debugging is not the subject of my post, any short insights into why I'm getting this result would be of interest. Here's the code I'm trying in the html template with a couple failing examples, and one suboptimal solution that does run mostly as hoped: <body onload="brython()"> <script type="text/python"> from browser import document, html # This line works and displays the contents of the .py file in browser, # used to rule out my staticfile options in settings document <= html.H1( open("{% static 'my_py_script.py' %}").read(), Id="main") # Here is one method I've tried that causes the browser to remain blank on … -
Django address city-district-neighbourhood choisefield
I have been trying to build a form in which can be chosen address city-district and neighborhood data according to city-district relation. For example when the user choose city then I want to see districts of the city. I am new at Django and coding and I've been searching and trying for a couple days. Here are my codes: Models.py: class Adresler(models.Model): il = models.CharField(max_length=50,verbose_name="il", null=True) ilçe = models.CharField(max_length=50,verbose_name="ilçe", null=True) mahalle = models.CharField(max_length=50,verbose_name="mahalle", null=True) PK = models.CharField(max_length=50,verbose_name="PK", null=True) def __str__(self): return self.mahalle class Fukara(models.Model): uyruk = models.CharField(max_length=50,verbose_name="Uyruk", null=True) kimlik_no = models.CharField(max_length=50,verbose_name="Kimlik No", null=True) ad_soyad = models.CharField(max_length=50,verbose_name="Ad Soyad", null=True) telefon = models.CharField(max_length=50,verbose_name="Telefon", null=True) meslek = models.CharField(max_length=50,verbose_name="Meslek", null=True) cinsiyet = models.CharField(max_length=50,verbose_name="Cinsiyet", null=True) yaş = models.IntegerField(verbose_name="Yaş", null=True) calisan_sayisi = models.IntegerField(verbose_name="Çalışan Sayısı", null=True) aylik_gelir = models.IntegerField(verbose_name="Aylık Gelir",null=True) durum= models.CharField(max_length=50,verbose_name="Durum", null=True) fert_sayisi = models.IntegerField(verbose_name="Aile Ferdi Sayısı", null=True) talep = models.CharField(max_length=150,verbose_name="Talepler", null=True) aciklama = models.CharField(max_length=150,verbose_name="Açıklama", null=True) adres_il = models.CharField(max_length=50, null=True,verbose_name="İl") adres_ilce = models.CharField(max_length=50, null=True,verbose_name="İlçe") adres_mahalle = models.CharField(max_length=50, null=True,verbose_name="Mahalle") adres_adres = models.CharField(max_length=50,verbose_name="Adres", null=True) kayit_eden = models.CharField(max_length=50,verbose_name="Kayıt Eden", null=True) kayit_tarihi = models.DateField(verbose_name="Kayıt Tarihi", null=True) dagitim_turu = models.CharField(max_length=50, verbose_name="Şahıs/Kurumsal", null=True) kurum_vergi_no = models.IntegerField(verbose_name="Vergi/Kimlik No", null=True) sorumlu_kisi = models.CharField(max_length=50, verbose_name="Sorumlu Kişi", null=True) il_listesi = models.ForeignKey(Adresler,on_delete=models.SET_NULL, null=True) def __str__(self): return self.kimlik_no "Adresler" class contains city-district-neighborhood data and in Fukara class adres_il … -
Apple SocialLoginView requires something called `id_token`?
My view: I am using the following view for apple 0auth. And I used very similar view for facebook and google auth, and they worked just fine. class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://www.My_FE_website.com/' client_class = AppleOAuth2Client # client_class = OAuth2Client But in this when the user make a post request to this view, it returns the following err. Error: File "/Users/apple/.local/share/virtualenvs/backend-kawWLPL_/lib/python3.9/site-packages/allauth/socialaccount/providers/apple/views.py", line 92, in parse_token identity_data = self.get_verified_identity_data(data["id_token"]) KeyError: 'id_token' -
Can't delete old objects after adding new one in django
old_objs = MyModel.objects.filter(user=request.user) MyModel.objects.create(user=request.user,...)# I must have to keep this line here. Because the new object is related to old objects old_objs.delete() I've a Model named MyModel. I filtered some old objects and keep them in a variable, then add a new object. Now if I want to delete old_objs, it delete all the objects including new object. I want to keep the new object and delete old objects. -
Listening onchange events on a dropdown to update a chart data list
I'm trying to figure it out how can I create an onchange event to listen to the value from the dropdown, so the chart will change it values depending on that id, for that I have the following elements: In views.py: def html(request, filename): #Data for the graph id = list(Device.objects.values_list('patientId', flat=True).distinct()) labels = list(Device.objects.values_list('hour', flat=True)) glucose_data = list(Device.objects.values_list('glucoseValue', flat=True)) data = glucose_data formatted_data = select_formatted_date(labels) lastPatientData = Device.objects.filter(patientId = id[-1]) #the last element added hourArray = [] glucoseArray = [] for item in lastPatientData: lastPatientHour = Device._meta.get_field('hour') lastPatientGlucose = Device._meta.get_field('glucoseValue') formattedHour = lastPatientHour.value_from_object(item) frt_hour = formattedHour.strftime('%Y-%m-%d %H:%M:%S') formattedGlucose = lastPatientGlucose.value_from_object(item) hourArray.append(frt_hour) glucoseArray.append(formattedGlucose) device_list = list(Device.objects.all()) for device in device_list: print(device) #f = DateRangeForm(request.POST) context = {"filename": filename, "collapse": "", "hourArray":hourArray, "glucoseArray": glucoseArray, "patientId": id, "dataSelection": formatted_data, "deviceList": device_list, "labels": json.dumps(labels, default=str), "data": json.dumps(data) } return render(request, f"{filename}.html", context=context) In forms.py, I have this, but I really don't know what to do with this data: from django import forms idsList = forms.ModelChoiceField(queryset = Device.objects.values_list('patientIId'),widget = forms.Select(attrs = {'onchange' : "myFunction()"})) my model is: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() And in the index.html, I have the following(in data … -
How to set API keys for non-authentication models in Django?
I am developing an inventory tracker for stores, where each store can have multiple outlets. I am using Django with the Django Rest Framework. Each store is an authentication model. As such, it can manage its respective outlets and settings by logging into the system. In the current state, each outlet uses the same token of the store model (provided by DRF) to connect and update inventory as sales are made. In my opinion, this creates a security vulnerability. For example, if a store has hundreds of outlets and one of the outlets' API key is exposed, all the outlets are exposed. Is there some way to generate an authentication token for each outlet? This way the stores can manage and, if required, renew the token of each outlet. Also, how would I validate this token in the DRF views and/or serializer? -
DRF: Creating mixin using different serializers & objects
I have two APIView classes with almost similar behaviour (and code). Different are only serializers and models object (Favorite & FavoriteSerializer for first class and PurchaseList and PurchaseListSerializer for second). As far as I understand it is a perfect usecase for mixin, according to DRF docs ([DRF: Creating custom mixins] 1https://www.django-rest-framework.org/api-guide/generic-views/). Unfortunately, I'm struggling with how to define mixin without the definition of serializer & obj in it. class FavoriteViewSet(APIView): def get(self, request, recipe_id): user = request.user.id data = {"user": user, "recipe": recipe_id} serializer = FavoriteSerializer( data=data, context={"request": request}, ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) def delete(self, request, recipe_id): user = request.user favorite_recipe = get_object_or_404( Favorite, user=user, recipe__id=recipe_id ) favorite_recipe.delete() return Response( "Рецепт удален из избранного", status.HTTP_204_NO_CONTENT ) class PurchaseListView(APIView): def get(self, request, recipe_id): user = request.user.id data = {"user": user, "recipe": recipe_id} serializer = PurchaseListSerializer( data=data, context={"request": request} ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) def delete(self, request, recipe_id): user = request.user purchase_list_recipe = get_object_or_404( PurchaseList, user=user, recipe__id=recipe_id ) purchase_list_recipe.delete() return Response( "Рецепт удален из списка покупок", status.HTTP_204_NO_CONTENT ) -
Having conflicting groups in Django Group Model
I have different groups in my Django Groups: for example: named Moderator and Reviewer. What I want to do is, if a user is in Moderator Group, the user shouldn't be in Reviewer Group. Now, I know that I can do this in different places like save_model() in ModelAdmin, etc. However, I want to prevent the assignment option in the Django Admin panel where you can assign users the groups and permissions as in below group selection. -
ImportError: cannot import name 'url' from 'django.conf.urls' django-rest-auth
error : from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -version Django==4.0.1 django-rest-auth==0.9.5 Pl help me.Thank you in advance url.py # Core Django imports from django.contrib import admin from django.urls import path, include from django.urls import re_path,include # from django.conf.urls import url,include from django.conf import settings # Rest framework imports from rest_framework import permissions # Simple JWT imports from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Heathy Living Guide API", default_version='v1', description="Heathy Living Guide", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = ( path('admin/', admin.site.urls), path('api/authentication/', include('apps.authentication.urls'),authentication'), path('api/users/', include('apps.users.urls'), name='users'), path('rest-auth/', include('rest_auth.urls')), # re_path(r'^rest-auth/', include('rest_auth.urls')) ) urlpatterns += [ path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc') ] -
Optimize Django tests with preloaded database
I am trying to reduce my CI usage and make my code cleaner by pre-loading my test database using a custom class. I had multiple files/classes that looked like this: class TestSomething(TestCase): def setUp(self): User.objects.create(...) def test_something(self): pass I converted them into: class TestSomething(PreloadedTestCase): def test_something(self): pass with a common PreloadedTestCase class: class TestSomething(TestCase): def setUp(self): User.objects.create(...) This does make the code cleaner and removes a lot of duplicate lines, but it seems to increase the CI execution time. Is PreloadedTestCase.setUp() run multiple times? If so, how can I have a common class that is run only once against the database? I looked into fixtures but it is only populating the database, I would have to query it to access my objects in the tests. -
What's the default value for a DecimalField in Django?
I'm adding a new DecimalField to my model, what value will it have by default in the database (if I don't specify the default explicitly)? amount = models.DecimalField(max_digits=15, decimal_places=3) I'm expecting it will be either NULL or 0.0 (or None or Decimal(0.000) in python), but which? Couldn't find this mentioned in the docs: https://docs.djangoproject.com/en/2.2/ref/models/fields/#decimalfield I'm using Django 2.2, but expect this is consistent across versions. -
'builtin_function_or_method' object has no attribute 'split' in django [closed]
def index(request): product = () catProds = Product.objects.values(category) cats = {items['category'] for items in catProds} for cat in cats: prod = Product.objects.filter(category=cat) product.append(prod) params = {'product':product} return render(request, 'shop/index.html', params) -
Django 4 and Unittest loader
We use Django for an online webshop, and want to upgrade to Django 4. However, since upgrading on a test branch, we have a problem, that I will highlight here. We serve two different markets, lets call them Market A and B :) Since these two markets can have different functionalities, our INSTALLED_APPS gets populated like so: MARKET_SPECIFIC_APPS = { MARKET_A: [ 'market_a.apps.MarketAConfig', 'payment_system_a.apps.PaymentSystemAConfig' ], MARKET_B: [ 'market_b.apps.MarketBConfig', 'payment_system_b.apps.PaymentSystemBConfig', ], } if MARKET in MARKET_SPECIFIC_APPS: # If there is a market-specific app, add it to INSTALLED_APPS INSTALLED_APPS += MARKET_SPECIFIC_APPS[MARKET] However, when running MARKET specific tests for each market, only MARKET_A passes. MARKET_B now throws an error, since upgrading from Django 3.2 to Django 4 RuntimeError: Model class payment_system_b.models.payment.Payment doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Meaning, this test is still run, and the test runner includes it in INSTALLED_APPS even tho it shouldnt. Is there any change from the Django 4 changelog im missing about this? Running these market-specific tests was working fine before upgrading to Django 4 -
What does set -e do in Nginx?
This is my code, I don't understand it completely. I would really appreciate your help #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' -
How can I resolve this issue with installing django2-semantic-ui=1.2.2 using pip?
I am trying to locally run an existing django application and install django2-semantic-ui==1.2.2 using the command: pip install django-semantic-ui=1.2.2. Here is the error I am getting: Using cached django2_semantic_ui-1.2.2.tar.gz (8.1 kB) ERROR: Command errored out with exit status 1: command: 'C:\Users\aakar\OneDrive\Documents\Data4Good\data4good-django\myenv\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"'; __file__='"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\aakar\AppData\Local\Temp\pip-pip-egg-info-u198istg' cwd: C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\setup.py", line 5, in <module> long_description = fh.read() File "c:\python3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 919: character maps to <undefined> ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/a1/76/e57ee8bf33259f832ae9f5c8d4d24a701516389f633efa37627922b6706a/django2_semantic_ui-1.2.2.tar.gz#sha256=a5efe89908c11e231dcea7cad249fd7bf629f7189d5621cd0d3bc82d154a9676 (from https://pypi.org/simple/django2-semantic-ui/) (requires-python:>=3.*). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement django2-semantic-ui==1.2.2 (from versions: 1.0.0b0, 1.0.0b1, 1.0.0b3, 1.0.0b4, 1.0.0, 1.0.1b0, 1.0.1, 1.1.0b0, 1.1.0, 1.1.1, 1.1.2, 1.2.0b0, 1.2.0b1, 1.2.0b2, 1.2.0b3, 1.2.0, 1.2.1b0, 1.2.1b1, 1.2.1b2, 1.2.1b3, 1.2.1b4, 1.2.1b5, 1.2.1b6, 1.2.1, 1.2.2b0, 1.2.2b1, 1.2.2) ERROR: No matching distribution found for django2-semantic-ui==1.2.2 All the other packages from requirements.txt were successfully installed. … -
Get input from front-end of the website and generate file corresponding in python
i am creating an website in which the users are going to input some form data and from the form data that the user given i will generate a excel file based on it using python, my python script is already done, but i dont know how i can connect it to the front-end / javascript so the i can pass the data to my python file script download the excel file to the user, i was looking at some django / flask tutorials but haven't found nothing that solves my problem, thanks for any reply in advance -
After intregation of django and reactjs blank page is rendered instead of component
I am working on full stack website I tried to integrate django with reactjs and was successful, but the problem is that it has returned a blank page instead of the reactjs component. this is output this is index.html inside build folder this is index.js from src -
'collections.OrderedDict' object has no attribute 'id'
My serializers: class SpeakerSerializer(serializers.ModelSerializer): class Meta: model = Speaker fields = ['id',...] class CourseSerializer(serializers.ModelSerializer): .... author = SpeakerSerializer(many=False, required=True) .... class Meta: model = Course fields = ['id', 'author',...] def create(self, validated_data): ... author = validated_data.get('author') ... course, _ = Course.objects.create(author=author.id, **validated_data) course.save() I'm sending POST request to this serializer and getting this response: Help please! course, _ = Course.objects.create(author=author.id, **validated_data) AttributeError: 'collections.OrderedDict' object has no attribute 'id'