Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override_settings not working at runtime with pytest DJANGO
In my settings.py file inside my django proyect I added a new constant ALLOW_SELF_REGISTRATION, that constant will allow or not a url in the proyect in the way: if settings.ALLOW_SELF_REGISTRATION: urlpatterns += [path( "self_registration/", views.self_registration_client, name="self_registration" ),] My problem is that I need to test when that constant is set to False in that case the url should not be added and a test to that url must raise a NoReverseMatch. I found that the override_settings is not working as expected, I do differents attemps to see if any could work, but no. Until now i tried: def test_constant_on_change_edit_urls_on_false(client): with override_settings(ALLOW_SELF_REGISTRATION=False): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) If I print the value of the constant in that test is set to True (as default) and not False as it should by the override_settings context manager. I need a way to override that constant at runtime inside the tests so I can test that functionality. Also tried: @override_settings(ALLOW_SELF_REGISTRATION=False) def test_constant_on_change_edit_urls_on_false(client): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) But also failed. There is any way to change that value at runtime during the tests? -
How connect Django with SQLServer 2008 r2
I tried connect Django with SQL Server 2008 r2 SP3. But when y run "python manage.py migrate" i get "django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Sintaxis incorrecta cerca de 'OFFSET'. (102) (SQLExecDirectW)")" My Settings: DATABASES = { "default": { "ENGINE": "mssql", "NAME": "xx", "USER": "xx", "PASSWORD": "xx", "HOST": "xx", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, }, } Version SQL Server: Microsoft SQL Server 2008 R2 (SP3) - 10.50.6000.34 (X64) Aug 19 2014 12:21:34 Copyright (c) Microsoft Corporation Express Edition with Advanced Services (64-bit) on Windows NT 6.3 (Build 19045: ) (Hypervisor) Version Python: 3.8.10 Version Django: 3.1.7 -
Create template with two forms
Good morning, I'm new to python and I have a problem with data entry. Some of the data is in a form and other data is selected and stored in another table. How can I load the two forms that are related in the same Template? I will appreciate if you can help me. Thank you forms.py from cProfile import label from dataclasses import fields from datetime import date, datetime from email.policy import default import imp from mailbox import NoSuchMailboxError from random import choices from django import forms import datetime,django.utils from django.contrib.admin.widgets import AdminTimeWidget, AutocompleteSelect from django.contrib.admin import widgets from .models import Detalle_remito, Personas, Recursos, Remito from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import NumberInput OPERADOR=( ('Fabiana', 'Fabiana'), ('Ma. Laura', 'Ma. Laura'), ('Adrian', 'Adrian'), ('Martín', 'Martín'), ('Andres', 'Andres'), ) USO=( ('INTERNO', 'INTERNO. Uso dentro de la Universidad'), ('EXTERNO', 'EXTERNO. Uso fuera de la Universidad') ) DIA_SEMANA=( ( '0', 'Lunes'), ( '1', 'Martes'), ( '2', 'Miercoles'), ( '3', 'Jueves'), ( '4', 'Viernes'), ( '5', 'Sabado'), ) class DetalleRemitoForm(forms.ModelForm): class Meta: model = Detalle_remito fields = {'id_remito', 'fecha', 'hora_retiro', 'hora_devolucion', 'id_recurso', 'estado'} class formularionuevo (forms.Form): uso=forms.ChoiceField(label="Uso del equipamiento ",choices=USO, widget=forms.widgets.RadioSelect(), initial='INTERNO') fecha_retiro=forms.DateField(label="Fecha retiro ",widget=NumberInput(attrs={'type': 'date'}), initial = datetime.date.today()) hora_retiro=forms.TimeField(label="Hora … -
How to define my aggregate function in django orm
I want to define an aggregate function, but I don't understand the example in Django document toally. -
Save zip to FileField django
I have a view that create two csv and my goal is to zip them and add to a model.FileField zip = zipfile.ZipFile('myzip.zip','w') zip.writestr('file1.csv', file1.getvalue()) zip.writestr('file2.csv', file2.getvalue()) I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format' Mymodel.objects.create(zip = File(open('myzip.zip','rb')) -
I can't use the command ' python manage.py makemigrations' in django VSC
I already did 'python manage.py migrations'. Now i want to create '0001_inital.py' file in migrations with the code 'python manage.py makemigrations'. Firstly this is my models.py; from django.db import models class Room(models.Model): #host = #topic = name = models.CharField(max_Length=200) description = models.Textfield(null=True, blank = True) #participants = updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) def __str__(self): return str(self.name) And here is the some of the errors that when i write 'python manage.py makemigrations'. File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 5, in class Room(models.Model): File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 8, in Room name = models.CharField(max_Length=200) File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\new_env\lib\site-packages\django\db\models\fields_init_.py", line 1121, in init super().init(*args, **kwargs) TypeError: Field.init() got an unexpected keyword argument 'max_Length' -
Converting two complex dictionary list to a dictionary
suppose I have two dictionary list below: all=[] lis1={ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } lis2={ 'code':'fropm', 'commandes':[ { 'date':'04-08-21', 'content':[ { 'article':'Article2', 'designation':'Designe2', 'quantity':3 } ] } ] } Now I add at list level my two dictionaries all.append(list1) all.append(liste2) to replace the [..] in {..} for a single list we can do all[0] But after adding the two lists and then doing all[0] we only have the first list whose [..] whose square brackets are replaced by {..} I would like to have this rendering { {...}, {...} } Is this possible?? -
python django app deploy error in cpanel?
I can't solve Cpanel 503 Error. If anyone can solve this problem please Help me. For hosting Django project I have tried many time with many python versions but showing same error -
How to use Filterset and paginateion in ApiView?
I am trying to use PageNumberPagination and FilterSet in APIView. But I have an error below in my code. object of type 'ListSerializer' has no len() How to implement this? Here are the code: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' class MyFilter(filters.FilterSet): class Meta: model = MyModel fields = '__all__' class MyAPIView(views.APIView, PageNumberPagination): def get(self, request, *args, **kwargs): filterset = MyFilter(request.query_params, queryset=MyModel.objects.all()) if not filterset.is_valid(): raise ValidationError(filterset.errors) serializer = MySerializer(instance=filterset.qs, many=True) paginate_queryset = self.paginate_queryset(serializer, request, view=self) return Response(paginate_queryset.data) Django 3.2.6 django-filter 22.1 djangorestframework 3.12.4 Python 3.8 -
What is the difference between Django timezone now and the built-in one?
I've just noticed this: >>> import datetime >>> from django.utils import timezone >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds 999989 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).seconds 86399 >>> 24*60*60 86400 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).days -1 >>> timezone.now() datetime.datetime(2022, 11, 17, 13, 1, 36, 913132, tzinfo=<UTC>) >>> datetime.datetime.now(tz=datetime.timezone.utc) datetime.datetime(2022, 11, 17, 13, 1, 41, 913958, tzinfo=datetime.timezone.utc) How do both options to get the current time with the UTC "timezone" differ? Why is the difference a positive number of seconds, but exactly negative one day? Can I replace timezone.now() by datetime.datetime.now(tz=datetime.timezone.utc)? -
In Celery Task, MyModel matching query does not exist
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error: myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist. I am particularly new to celery and docker so not sure what am I doing wrong. Celery is set up correctly, I have made sure of that. Following are the broker_url and backend: CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' This is my docker-compose.yml file: version: "3.8" services: redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - npm-nw - braythonweb-network braythonweb: build: . command: > sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn braython.wsgi:application -b 0.0.0.0:8000 --workers=1 --timeout 10000" volumes: - .:/code ports: - "8000:8000" restart: unless-stopped env_file: .env networks: - npm-nw - braythonweb-network celery: build: . restart: always container_name: cl01 command: celery -A braython worker -l info depends_on: - redis networks: - npm-nw - braythonweb-network networks: braythonweb-network: npm-nw: external: false I have tried few things from different stackoverflow posts like apply_async. I have also made sure that my model existed. -
I want create comment section that can only logged in users can use but i have this problem
cannot unpack non-iterable bool object profile = Profile.objects.get(Profile.user == request.user) this is my models.py in account app and blog app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعهدهنده'), ('designer', 'طراح پروژه'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True) def __str__(self): return f'{self.user.get_full_name()}' class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) and this is my views.py for comments: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(Profile.user == request.user) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return redirect('post_detail', slug=post.slug) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags}) Is there any solution for this problem? -
The view main.views.view didn't return an HttpResponse object. It returned None instead
I have a upload function. But when I try to upload the file. I get this error: ValueError at /controlepunt140 The view main.views.view didn't return an HttpResponse object. It returned None instead. So this is the template:" <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" onclick="test()" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </form> and views.py: def post(self, request): submitted_form = ExcelForm(request.POST, request.FILES) content_excel = '' if request.POST.get('form_excel') is not None: if submitted_form.is_valid() and request.POST: excel_file = request.FILES["upload_file"] excel_file.save() wb = openpyxl.load_workbook(excel_file) worksheet = wb['Sheet1'] print(worksheet) excel_data = list() content_excel = excel_data return render(request, "main/controle_punt140.html", { 'form': ExcelForm(), "content_excel": content_excel, }) return render(request, "main/controle_punt140.html", { "form": submitted_form, "content_excel": content_excel, }) and forms.py: class ExcelForm(forms.Form): upload_file = forms.FileField() Question: how resolve this? -
Get component schema for a specific endpoint with drf spectacular
I want to use drf spectacular to get the component schema of a specific endpoint. For example, if I have the endpoint api\articles that supports POST with two CharFields field1 and field2. I then want another endpoint such as api\articles\schema\post where I could use GET to return an autogenerated JSON like this: { "type": "object", "description": "description of article", "properties": { "field1": { "type": "string", "maxLength": 255 }, "field2": { "type": "string", "maxLength": 255 } -
Django & gunicorn in docker-compose consume alot of resources ( Memory - CPU )
I have 3 containers that share the same code (WSGI - ASGI - Celery) Everything works fine but when I check the docker stats docker stats I found that WSGI consumes a lot more resources than the rest The containers are deployed on DigitalOcean droplet without domain just IP docker-compose.yml version: "3.7" services: db: build: context: . dockerfile: ./docker/database/master/Dockerfile restart: always ports: - ... volumes: - ... environment: - ... replica: build: context: . dockerfile: ./docker/database/replica/Dockerfile restart: always environment: - ... replica1: build: context: . dockerfile: ./docker/database/replica/Dockerfile restart: always environment: - ... backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile_wsgi entrypoint: /app/docker/backend/wsgi_entrypoint.sh volumes: - static_volume:/app/backend/server/django_static - static_image:/app/backend/server/media expose: - 8000 environment: - ... depends_on: - db links: - redis - db - cere asgiserver: restart: always build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/asgi.entrypoint.sh volumes: - static_volume:/app/backend/server/django_static - static_image:/app/backend/server/media environment: - ... depends_on: - db links: - redis - db - cere expose: - 9000 redis: image: "redis:alpine" restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf expose: - 6379 cere: image: "redis:alpine" restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis_1.conf:/usr/local/etc/redis/redis.conf expose: - 6380 celery: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile_celery entrypoint: /app/docker/backend/celery-entrypoint.sh environment: - ... depends_on: - asgiserver - backend … -
creating an admin user using django
I was creating an admin user account, when it got to create password my keys stopped working!!I even rebooted my system and started from top boom it happened again tried to create password on django admin user account? -
PostgreSQL queries slow after upgrading django project from 2.X to 3.2
We just upgraded our project from Django 2.x to 3.2 and are experiencing queries that are much slower. We are not quite sure what is handled differently, but if we EXPLAIN ANALYZE some query on a local database before the migration and one after, we see very different results with regards to time. Example Query: SELECT SUM("journals_journalmutation"."amount") AS "sum" FROM "journals_journalmutation" INNER JOIN "ledger_ledgeraccount" ON ("journals_journalmutation"."ledger_account_id" = "ledger_ledgeraccount"."id") INNER JOIN "journals_purchasejournalentryline" ON ("journals_journalmutation"."purchase_journal_entry_line_id" = "journals_purchasejournalentryline"."id") WHERE ("ledger_ledgeraccount"."master_ledger_account_id" IN (1611, 1612, 1613) AND "journals_purchasejournalentryline"."journal_entry_id" = 370464 AND "journals_journalmutation"."credit_debit" = 'DEBIT' AND "ledger_ledgeraccount"."master_ledger_account_id" IN (1611, 1612, 1613)) Here is the result of EXPLAIN ANALYZE on that query on the database before migration: Aggregate (cost=19.83..19.84 rows=1 width=32) (actual time=0.008..0.008 rows=1 loops=1) -> Nested Loop (cost=1.28..19.82 rows=1 width=6) (actual time=0.006..0.007 rows=0 loops=1) -> Nested Loop (cost=0.85..17.70 rows=4 width=10) (actual time=0.006..0.006 rows=0 loops=1) -> Index Scan using journals_purchasejournalentryline_ea982348 on journals_purchasejournalentryline (cost=0.42..8.44 rows=1 width=4) (actual time=0.005..0.006 rows=0 loops=1) Index Cond: (journal_entry_id = 370464) -> Index Scan using pjel_idx on journals_journalmutation (cost=0.43..9.25 rows=1 width=14) (never executed) Index Cond: (purchase_journal_entry_line_id = journals_purchasejournalentryline.id) Filter: ((credit_debit)::text = 'DEBIT'::text) -> Index Scan using ledger_ledgeraccount_pkey on ledger_ledgeraccount (cost=0.42..0.53 rows=1 width=4) (never executed) Index Cond: (id = journals_journalmutation.ledger_account_id) Filter: ((master_ledger_account_id = ANY ('{1611,1612,1613}'::integer[])) … -
Docker Mailhog with Docker django error: [Errno 111] Connection refused
I have 2 containers running through docker-compose, one with Django, the other with Mailhog. But when I send_mail through Django python manage.py runserver, it is possible to send, if i run a docker-compose up when I send email this error is returned: [Errno 111] Connection refused My docker-compose is: services: mailhog: image: mailhog/mailhog logging: driver: 'none' # disable saving logs ports: - 1025:1025 # smtp server - 8025:8025 # web ui networks: - my_net api: build: . container_name: my_api command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/src ports: - '8000:8000' env_file: - '.env' depends_on: - mailhog networks: - my_net networks: my_net: My env file is: EMAIL_HOST = '0.0.0.0' EMAIL_PORT = '1025' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' What should I do? -
boto3 conflict with endpoint url and bucket causing error
The correct file url from S3: https://video-sftp.s3.amazonaws.com/600.mp4 Now when attempt to generate presigned url with boto3 the file url is incorrect: https://video-sftp.s3.amazonaws.com/video-sftp/600.mp4 the bucket name is being appended as directory? AWS_S3_ENDPOINT_URL='https://video-sftp.s3.amazonaws.com' AWS_S3_REGION_NAME='us-east-1' Here is code: def post(self, request, *args, **kwargs): session = boto3.session.Session() client = session.client( "s3", region_name=settings.AWS_S3_REGION_NAME, endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) url = client.generate_presigned_url( ClientMethod="put_object", Params={ "Bucket": "video-sftp", "Key": f"{json.loads(request.body)['fileName']}", }, ExpiresIn=300, ) return JsonResponse({"url": url}) It appears to be looking for directory video-sftp in the bucket video-sftp? How do i solve? I've tried changing the endpoint url to https://s3.us-east-1.amazonaws.com, which results in 403 forbidden. I have updated CORs policy to allow PUT. -
How to setup django rest framework app outside project
I want to setup app app2 outside project directory. If you check following screenshot, I have created djnago project project, inside this project, created app app1 and created app 'app2' outside project. Now how to include app2 and urls.py in project settings and urls.py. INSTALLED_APPS = [ . . '../common_functions/app2', ] I tried above but getting errors: **TypeError: the 'package' argument is required to perform a relative import for ../common_functions/app2 -
Deleting User not working due to ManyToMany fields on another app
I am using django-tenants and django_tenant_users with the following apps (settings.py): SHARED_APPS = ( 'django_tenants', 'django.contrib.contenttypes', 'tenant_users.permissions', # Defined in both shared apps and tenant apps 'tenant_users.tenants', # defined only in shared apps # everything below here is optional ... 'tenants', # list the app where your tenant model resides in. Must NOT exist in TENANT_APPS 'apps.users', # Custom app that contains the new User Model. Must NOT exist in TENANT_APP 'debug_toolbar', ) TENANT_APPS = ( # for django-tenant-users 'django.contrib.auth', # Defined in both shared apps and tenant apps 'django.contrib.contenttypes', # Defined in both shared apps and tenant apps 'tenant_users.permissions', # Defined in both shared apps and tenant apps # your tenant-specific apps 'apps.jobs', ) And this is my jobs models.py: class Job(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) title = models.CharField(_('Title'),max_length=80, blank=True, default="") details= models.CharField(_('Details'), max_length=250, blank=True, default="") jobarea = models.ForeignKey('JobArea', verbose_name="Job Area", on_delete=models.CASCADE, null=True) def __str__(self): return self.title class JobArea(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) name = models.CharField(_('Title'),max_length=80, blank=True, default="") details = models.CharField(_('Details'), max_length=250, blank=True, default="") owners = models.ManyToManyField(settings.AUTH_USER_MODEL) def __str__(self): return self.name class Urel(models.Model): employee = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) When I try to delete a User that is on the public tenant, I get the following error: relation "jobs_jobarea_owners" does not exist … -
Update Django model field when actions taking place in another model
I want to make changes in a model instance A, when a second model instance B is saved,updated or deleted. All models are in the same Django app. What would be the optimal way to do it? Should I use signals? Override default methods[save, update,delete]? Something else? Django documentation warns: Where possible you should opt for directly calling the handling code, rather than dispatching via a signal. Can somebody elaborate on that statement? -
Record not getting edited in django form using instance
The model is not getting updated in the database while using the below methods. This is upload form in views This is my edit function in views Tried editing the record but it is not getting updated. -
Auto hide Row / Column of Table if specific field exists in MySQL Database using Django
I am working on a Django project and I am stuck in a situation where I want to hide a row in a table if specific entity exists in column in database. I am using MYSQL database. I want auto hide row without clicking on any button or any checkbox. page.html: <table border="2"> <tr> <th> ID</th> <th> NAME</th> <th> PASSWORD</th> <th> IP</th> <th>PORT</th> </tr> {% for data in Cvs_logs %} <tr> <td>{{data.id}}</td> <td>{{data.user}}</td> <td>{{data.pass}}</td> <td>{{data.ip}}</td> <td>{{data.port}}</td> </tr> {% endfor %} </table> views.py: def home_view(request): auth = Cvs_logs.objects.all() return render(request, 'page.html', {'Cvs_logs': auth }) models.py: class Cvs_logs(models.Model): id = models.BigIntegerField ip = models.CharField(max_length= 100) port = models.CharField(max_length= 100) user = models.CharField(max_length= 100) pass = models.CharField(max_length= 100) class Meta: db_table = "xyz" The condition is if name == 'abc', then It should hide data automatically without clicking on any button -
Call one serializer's update() method from another serilaizer's create() method
I have 2 serializers serializer_1 and serializer_2 which are both model serilizer i want to execute update method of serializer_1 from create method of serializer_2 how can i achieve that? class serializer_1(serializers.ModelSerializer): date = serializers.DateTimeField(required=False, allow_null=True) ispublic = serializers.BooleanField(allow_null=False) details_api_url = serializers.SerializerMethodField() dispute_types = OtherSerializer(many=True, required=False, write_only=True) nature_of_dispute_list = serializers.SerializerMethodField() plaintiff = OtherSerializer(many=True, required=False, write_only=True) defendant = OtherSerializer(many=True, required=False, write_only=True) claims_rep = OtherSerializer(many=True, required=False, write_only=True) class Meta: model = Media fields = "__all_" def update(self, instance, validated_data): date = validated_data.pop('close_out_date', None) plaintiff_data = validated_data.pop('plaintiff', []) defendant_data = validated_data.pop('defendant', []) claims_rep_data = validated_data.pop('claims', []) is_summary_public_previous = instance.is_summary_public obj = super().update(instance, validated_data) return obj class serializer_2(serializers.ModelsSerializer): class Meta: model = Fedia fields = "__all__" def create(self, validated_data): request = self.context['request'] serilizer_1_data = validated_data.pop('serialzer_1_data', None) is_final = validated_data.get('is_final') serializer_1_object = Media.object.create(**serializer_1_data) if is_final: **Call Serializer Update method**