Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Not able to retrieve/fetch versatileImage link (Cropped URL) in SerializerMethodField()
class GetUserImageOneSerializer(serializers.ModelSerializer): class Meta: image_one = VersatileImageFieldSerializer( sizes=[ ('medium_square_crop', 'crop__400x400'), ] ) model = UserImage fields = ('image_one',) class ChatUserSerializer(serializers.ModelSerializer): chatImage = serializers.SerializerMethodField() class Meta: model = Chat fields = ('roome_name','chat_user_one','chat_user_two','lastUpdated','chatImage') def get_chatImage(self, obj): image=UserImage.objects.filter().first() //(for Test) serializer = GetUserImageOneSerializer(image) return serializer.data Here I am trying to pass image of the user in chat serializer ('ChatImage') .For better behavior in UI I need square crop image ,so I tried to use nested serializer ('GetUserImageOneSerializer' inside 'ChatUserSerializer'). But I am getting normal URL only . can you help me to find better way to implement my idea :) OUT PUT : [ { "roome_name": "BISM1000BISM1000", "chat_user_one": 6, "chat_user_two": 5, "lastUpdated": "2021-12-11T10:29:21.589947Z", "chatImage": { "image_one": "/media/userimage/team-1.jpg" } } ] -
Django deploy to production with nginx gunicorn and SSL - How to deploy?
I am trying to deploy my Django app to my domain but I do not know how to set this up, I currently have the app running in development only. There are many components involved, like Nginx, gunicorn, uvicorn, and apparently, I have to set up some SSL certificates. The relevant files: This is my folder structure now, and it seems like I need to add the certificates to certs/, which is currently empty: .rw-r--r-- 53k 5 Dec 13:28 -- .coverage drwxr-sr-x - 11 Dec 12:32 -- .git/ .rw-r--r-- 52 2 Dec 12:05 -- .gitignore .rw-r--r-- 3.0k 11 Dec 01:05 -- .gitlab-ci.yml drwxr-sr-x - 2 Dec 21:09 -- app/ drwxr-sr-x - 10 Dec 15:06 -- bank/ drwxr-sr-x - 11 Dec 12:26 -- certs/ drwxr-sr-x - 6 Dec 14:40 -- config/ drwxr-sr-x - 2 Dec 21:33 -- data/ .rw-r--r-- 197k 5 Dec 13:28 -- db.sqlite3 .rw-r--r-- 182 11 Dec 01:05 -- db_dev.env .rw-r--r-- 185 10 Dec 15:06 -- db_prod.env .rw-r--r-- 185 10 Dec 15:06 -- db_test.env drwxr-sr-x - 2 Dec 19:57 -- dbscripts/ .rw-r--r-- 733 10 Dec 15:06 -- docker-compose.yml .rw-r--r-- 378 10 Dec 15:06 -- Dockerfile .rw-r--r-- 1.0k 11 Dec 12:03 -- entrypoint.sh drwxr-sr-x - 4 Dec 00:23 -- htmlcov/ … -
Django CORS issue with flutter web
I want to connect flutter web with Django server. flutter with mobile works well, but I can't solve the problem about flutter web. when I run server with my ipv4 Django python manage.py runserver 192:168:0:9:8000 Flutter Uri.parse("http://192.168.0.9:8000/api/buildingdata/"), headers: {"Access-Control-Allow-Origin": "*"}); flutter run -d chrome --web-port=8000 Mobile version works well, but web version makes CORS error. Access to XMLHttpRequest at 'http://192.168.0.9:8000/api/buildingdata/' from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field access-control- allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. browser_client.dart:74 GET http://192.168.0.9:8000/api/buildingdata/ net::ERR_FAILED I tried to find solutions but none of them worked, such as web-hostname command(this command can't even run flutter), deleting flutter_tools.stamp and adding disable-web-security Also I've tried to disable chrome CORS. This is my django settings about cors settings.py 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_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) Where should I fix to solve CORS error? -
django rest api permission problem with post and put
I have a problem with post and put request. My requests with axios in react: handleSubmit() { axios.post('http://127.0.0.1:8000/api/tasks/',{ headers:{"Authorization":`Token ${this.state.token}`}, author:this.state.id, title:this.state.title, desc:this.state.desc, done:false, }) .then( response =>{console.log(response);} ) .then( ()=>{window.location.reload(false);} ) } Everything works fine but when i change AllowAny to IsAuthenticated in code below: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } i'm getting an error like this POST http://127.0.0.1:8000/api/tasks/ 403 (Forbidden) dispatchXhrRequest @ xhr.js:210 xhrAdapter @ xhr.js:15 dispatchRequest @ dispatchRequest.js:58 request @ Axios.js:108 Axios.<computed> @ Axios.js:140 wrap @ bind.js:9 handleSubmit @ TaskCreate.js:41 onClick @ TaskCreate.js:73 callCallback @ react-dom.development.js:3945 invokeGuardedCallbackDev @ react-dom.development.js:3994 invokeGuardedCallback @ react-dom.development.js:4056 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4070 executeDispatch @ react-dom.development.js:8243 processDispatchQueueItemsInOrder @ react-dom.development.js:8275 processDispatchQueue @ react-dom.development.js:8288 dispatchEventsForPlugins @ react-dom.development.js:8299 (anonymous) @ react-dom.development.js:8508 batchedEventUpdates$1 @ react-dom.development.js:22396 batchedEventUpdates @ react-dom.development.js:3745 dispatchEventForPluginEventSystem @ react-dom.development.js:8507 attemptToDispatchEvent @ react-dom.development.js:6005 dispatchEvent @ react-dom.development.js:5924 unstable_runWithPriority @ scheduler.development.js:468 runWithPriority$1 @ react-dom.development.js:11276 discreteUpdates$1 @ react-dom.development.js:22413 discreteUpdates @ react-dom.development.js:3756 dispatchDiscreteEvent @ react-dom.development.js:5889 createError.js:16 Uncaught (in promise) Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.onloadend (xhr.js:66) In addition to that, get requests work correctly even if i change to isAuthenticated. const getTasks = () =>{ //this works fine axios.get("http://127.0.0.1:8000/api/tasks/"+`user/${id}/` ,{headers:{"Authorization":`Token ${props.token}`}}) .then( response => { setTasks(response.data); … -
I am not receiving any error when i run my application but when a user registers he gets added to both client and worker tables. instead of one table
Someone show me where my code is not correct. during registration, am having a user who is a client getting added to both client and worker tables, while a worker is getting added to both client and worker tables, which is not okay. Am not getting any traceback error when i run the app the duplication could mean that there is code which is running twice signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.dispatch.dispatcher import receiver from .models import Worker,Client @receiver(post_save, sender=User) def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='Client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, email=instance.email, ) print('Profile created!') @receiver(post_save, sender=User) def worker_profile(sender, instance, created, **kwargs): if created: Worker.objects.create( user=instance, name=instance.username, email=instance.email, ) models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ # Create your models here. class Client(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Worker(models.Model): CATEGORY = ( ('Plumber', 'Plumber'), ('Electrician', 'Electrician'), ('Cleaner', 'Cleaner'), ) user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = … -
How to optimize a DjangoORM reverse foreign key query?
I have the following relationships: I'm trying to select all tasks with all instances and their vehicle. This however is a very slow query. To my understand I have to use prefetch_related because it's a OneToMany relationship. My InstanceModel has a reverse foreign key to Task: task = models.ForeignKey(TaskModel, on_delete=models.CASCADE, related_name="instances") I've attempted a query like this in DjangoORM: TaskModel.objects.filter(department_id=department_id).prefetch_related("instances", "instances__vehicle") But it's very slow. Is there any way to optimize this or due the relationship inherently restrict this query pattern? Running in Django 3.x -
How to convert ' to quotes in javascript?
I am trying to pass a python list with string values from views.py to the template where a javascript uses the same for labels of a pie chart(plotly). The issue is when the list is received at the front-end, the list is getting the hexcode of the quote which is ' instead of the quotes. How to convert it to quote? Here is the snippet: var trace1 = { x: {{labels}}, y: {{values}}, marker:{ color: ['rgba(204,204,204,1)', 'rgba(222,45,38,0.8)', 'rgba(204,204,204,1)', ] }, type: 'bar' }; Now, i am getting the values for 'labels' as: [&#x27;One&#x27;, &#x27;Two&#x27;, &#x27;Three&#x27;] Instead of: ['One','Two','Three'] Just wanted to know are there any methods to avoid this easily instead of using string replace methods? -
Get first element from many to many relationship django in template
I'm trying to get the first element from queryset which is returned by a Model Field which is a ManyToManyField right in the template. models.py class CraftImage(models.Model): image = models.ImageField(upload_to='crafts_images/', null=True) class Craft(models.Model): title = models.CharField(max_length=100, null=False, blank=False) images = models.ManyToManyField(CraftImage, blank=True, related_name='craft_images') views.py def work_all(request): crafts = Craft.objects.all() context = { 'crafts': crafts, } template.py {% for craft in crafts %} <div style="background-image: url('{% static 'craft.images[0].image.url' %}');"></div> {% endfor %} Something like this. I've also tried following some solutions I found which didn't work for me such as.. views.py crafts = Craft.objects.all() images = Craft.objects.values_list('images').first() print(images) context = { 'crafts': crafts, 'images': images } templates.py {% for craft in crafts %} <div style="background-image: url('{% static 'images.image.url' %}');"></div> {% endfor %} -
Running deferred SQL in django
Whenever i run python3 manage.py makemigrations python3 manage.py migrate I get this Running deferred SQL... I am not getting any error but curious to know will it affect in long term? Any way to remove this? My custom user model is from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): ... -
Django ORM data based on max date group
model class quote(models.Model): id = models.AutoField(primary_key=True) stock = models.ForeignKey(stock, related_name='stock', on_delete=models.CASCADE) price = models.DecimalField(max_digits=30,decimal_places=5) valid_till = models.DateTimeField() created_at = models.DateTimeField() #time updated_at = models.DateTimeField(blank=True,null=True) ex data id stock price valid_till created_at 1. 1. 200. 09 April. 09 April 2. 1. 300. 10 April. 09 April output desire id stock price valid_till created_at 2. 1. 300. 10 April. 09 April I need only record for max date of every stock currently doing quote.objects.values('stock__symbol').annotate(max_date=Max('valid_till')) but still not able to think about proper solution -
Django leaflet marker icon doesn't appear on Heroku
I have deployed my Django app to Heroku but when I want to fill the location field, the marker icon doesn't appear even though I have used whitenoise to serve the static files. It is working locally though. This is the . Here's how I set my whitenoise INSTALLED_APPS = [ ..., 'whitenoise.runserver_nostatic' ] MIDDLEWARE = [ ..., 'whitenoise.middleware.WhiteNoiseMiddleware' ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' -
Filter a field with timestamp (datetime) using today's date in Django
I have a Django model with a timestamp field. I want to filter and get the number of rows containing today's date. The timestamp field contains date, time and time zone. I tried this: today_date = date.today().strftime("%Y-%m-%d" ) Pending = tablename.objects.filter(timestamp=today_date,).count() But I got zero (0). Thank you. -
Django Rest framework url static files missing?
I got an api with rest framework but the field img missing the host url .ex:localhost:... The img field should have localhost: ... / images / ... But it only has /images/.. How can I change it to urlhost/images/.. Models.py class Product(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. productcode = models.CharField(db_column='ProductCode', max_length=200, blank=True, null=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=200) # Field name made lowercase. price = models.FloatField(db_column='Price') # Field name made lowercase. img = models.FileField(db_column='IMG', max_length=200) # Field name made lowercase. description = models.CharField(db_column='Description', max_length=2000, blank=True, null=True) # Field name made lowercase. stock = models.IntegerField(db_column='Stock') # Field name made lowercase. createdate = models.DateField(db_column='CreateDate',default=dateupdate()) # Field name made lowercase. brandname = models.ForeignKey(Brand, models.DO_NOTHING, db_column='BrandName') # Field name made lowercase. Views.py @api_view(['GET']) def CartdetailsView(request): username = request.user.username queryset = Cartdetails.objects.filter(username=username) serializer = CartdetailsSerializer(queryset,many=True) return Response(serializer.data) -
Django template variable in html
i want to adjust the width of processbar with variable cresource.cpu_avail_percent, how can i add style tag my code {% for cresource in c_resources %} <div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:{{cresource.cpu_avail_percent}};"> </div> {% endfor %} i'm using django 3.2.6 -
extract children with a given condition - Django MPTT and Django rest framework
In this tree I want to do a query so that only the first generation of the red circle is extracted. But the condition is that the value of each circle must be greater than zero, ie the green circles: Serializers: class CircleBaseSerializer(serializers.ModelSerializer): class Meta: model = Circle fields = ('id', 'value') class CircleChildrenSerializer(CircleBaseSerializer): class Meta(CircleBaseSerializer.Meta): pass class CircleParentSerializer(CircleBaseSerializer): children = CircleChildrenSerializer(many=True) class Meta(CircleBaseSerializer.Meta): pass View: class CircleViewSet(ReadOnlyModelViewSet): serializer_class = CircleParentSerializer queryset = Circle.objects.all() def get_queryset(self): id = self.kwargs["id"] u=Circle.objects.get(pk=id) Certainly result is [5(1,0,3)] that is not desirable. How can I do this query? -
Leveraging django auth.views LogoutView
I have two usertypes a and b how should i leverage the auth views i.e LogoutView that django provides how can my view look with what methods and attributes i should use and how should i set my login_url and etc this is how my function based view looks now.. views.py @login_required def logout(request): if request.user.usertype_a: logout(request) return redirect(reverse('user_a')) else: logout(request) return redirect(reverse('user_b')) -
'Settings' object has no attribute Django Restframework
I know this question has been asked before. But i am unable to understand the answer. I have defined an environment variable in settings.py s3path=env('S3PATH') Then i call it in views.py from django.conf import settings as conf_settings conf_settings.s3path but i am getting this error 'Settings' object has no attribute 's3path' -
When to use API vs SMTP in Django
Can API be used to replace SMTP for mail sending in Django especially for things like reset password and mail confirmation. I will really love if I can get clarification on a topic in django. I am a newbie to django and when it comes to sending mail I register for Mailgun and used the API since I have used requests before but picking up django to work with I am trying to do user registration using DJ-Rest-auth and django_allauth and there is thing about configuring email backend using SMTP. my question is Can i do without using SMTP for django_allauth if Yes a workflow how to connect my password reset to use the api for mail. I can easily pass in the mail function to serve as an alert in the views when user registers -
selection query based on combo box input django
I have two models; City and location that I want to connect together. The models for them are as follows: class City(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) city_id = models.IntegerField(default=0) class Meta: ordering = ['ordering'] def __str__(self): return self.title class Location(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) location_id = models.IntegerField(default=0) city_id_fk = models.ManyToManyField(City) class Meta: ordering = ['ordering'] def __str__(self): return self.title First you select which city and then based on the combo box selection you are displayed locations. Im connecting the two tables using city_id_fk. Now i want to write a query for selection based on the city selected. How can I do that? -
Django - Get a single queryset values list from two related models
I have an user model class User(AbstractBaseUser): name = models.CharField(max_length=100, default='Default') email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) and a related SecondaryEmails model class SecondaryEmails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='secondary_emails') email = models.EmailField() is_validated = models.BooleanField(default=False) Now I want to create a method to get a values_list containing both the User model's email and all the emails stored in the related SecondaryEmails model. I am able to get a values_list containing only the email of the User model >>> User.objects.filter(email='test@gmail.com').prefetch_related('secondary_emails').values_list('email') >>> <QuerySet [('test@gmail.com',)]> The related SecondaryEmails model contains another two emails 'a1@gmail.com', 'a2@gmail.com'. I wanted these two emails also to be appended in the values_list() like the following: <QuerySet [('test@gmail.com',), ('a1@gmail.com',), ('a2@gmail.com',)]> Thanking you in advance. -
makemigrations can't detect change in django
I know there are a lot of similar questions: but I will describe my problem as simply as I can. This is the app I want to migrate. This is my setting.py This is what happens when I type in makemigrations(after I add a field in my model) This is what happens when I type in showmigrations(after I add a field in my model) I have reinstall django using pip, I have created new app , I have created new project,new venv, I even have reinstall python itself, all same story. I suspect my django source code has been corrupted, but when I install django using pip, it use file that is downloaded before instead download new file. Trust me, I have tried all the way you a newbie could possibly tried, could someone tell me how to redownload django itself or someone who is way smarter than me know what's going on right now. Thx! -
unable to filter() users with their date_joined field
I want to count all the users whose date_joined matches with 'today's' date. I have two users who have today's date in the date_joined field but the count always returns zero. I am perhaps not filtering the data correctly. These are the waays that I have tried to filter the data models class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique= True) full_name = models.CharField(max_length=255) phone_no = models.CharField(max_length=10, blank= True) address = models.CharField(max_length=500, blank= True) plan = models.CharField(max_length=255, blank= True) age = models.CharField(max_length=2, blank= True) date_joined = models.DateTimeField(default=timezone.now) views from datetime import datetime, date def dashboard(request): all_users = CustomUser.objects.all().exclude(is_staff = True).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today()).count() print(all_users_bydate) all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() even tried to explicitly filter all_users_bydate = CustomUser.objects.all().filter(date_joined= date(2021, 12, 11)).count() all of these ways did not work at all and always retuned zero. Please rectify me what I am doing wrong. -
Python - Django: select mulitple fields from different models to serialize into one json result
I'm currently working in my first Django project and am using the authentication mechanism that is included with Django. I currently have a game model with a foreign key relationship to a user in the auth_user table. Here are the following fields: class Game(models.Model): game_id = models.UUIDField(default=uuid.uuid4, editable=False, max_length=10) host = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) join_code = models.CharField(max_length=100, null=True) active = models.BooleanField(default=True) I currently have a view method that just grabs all of the active game objects, and then passes those results into a serializer that serializes the data to be returned to the client. def get(self, request, format=None): games = Game.objects.filter(active__exact=True) serializer = GameSerializer(games, many=True) return Response(serializer.data) I want to add the username and email fields that are in AUTH_USER_MODEL to the results to be serialized, but I haven't been able to find examples of adding specific fields from a related model to the results that are serialized. Basically, I'm trying to figure out the django model equivalent of the following SQL statement select u.username, u.email, g.* from game g inner join AUTH_USER_MODEL u on u.user_id = g.host_id Finally, once I have the results from that sort of query, how would I serialize the combined objects? Do I need … -
Add and delete in one instance django Formset
I have a formset which generally works (Add, Delete, Edit) items except when I decide to Add and Delete(or vice versa) in one instance, the formset throws the 'id': ['This field is required.'] error. Below are prints of request.POST: When it works: <QueryDict: {'csrfmiddlewaretoken': ['lnEG6qbrWRg4NdkKwg1UU86KTBuIgJIc4ZqJAWvZpASgxECnicmlUmVhJIInvqEJ'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['7'], 'form-1-year': ['2024'], 'form-2-id': ['8'], 'form-2-year': ['2025']}> When it does not work (I deleted 2024 and added 2026): <QueryDict: {'csrfmiddlewaretoken': ['fh0mPGYzVt0AOjpE5Q9JuTp1zuqwNCuMYTMpjci7ocCMyKHhRMuau7eypBEb2jqj'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['8'], 'form-1-year': ['2025'], 'form-2-id': [''], 'form-2-year': ['2026']}> [{}, {}, {'id': ['This field is required.']}] Model: class Year(models.Model): year = models.CharField(max_length=100, null=True) user = models.CharField(max_length=300, null=True, blank=True) Forms: YearFormset = forms.modelformset_factory( Year, fields=('year',), extra=1, widgets={ 'year': forms.TextInput( attrs={ 'require': 'required', 'class': 'form-control', 'placeholder': 'Enter Year here' }) } ) View: def year(request): year_items = Year.objects.filter(user=1) year_set = YearFormset(queryset=year_items) year_set.extra = 0 if year_items else 1 context = {'years':year_set} if request.method == 'POST': print(request.POST) submit_year = YearFormset(request.POST) if submit_year.is_valid(): Template: <form method="POST"> {% csrf_token %} <br> {{ years.management_form }} {% for year in years %} <div class="form-row"> <div class="col-4"> <div class="input-group"> {{year.id}} {{year.year}} <button class="btn btn-success add-form-row">+</button> </div> <br> </div> … -
Serialize and create one-to-one relation with parent_link true in django and django rest framework
How to save the object with one-to-one relation and having parent_link=True using serializer. Below are my models and serializer having some fields from the actual model that I wanted to implement. I am not able to save the 'user' relation in the database. It is throwing the integrity error. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) password = models.TextField() is_active = models.BooleanField(default=False) class UserProfile(User): class Meta: db_table = 'user_profile' user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True, primary_key=True) address = models.TextField(null=True) dob = models.DateField() language = models.CharField(max_length=50, null=True) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user', 'address', 'dob', 'language'] And the requested data looks like this. { "email": "abc@pqr.com", "password": "1234", "dob": "2021-12-11", "language" : "English" }