Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Superuser active is turned to False, how can I login to my django admin
Superuser active is turned to False, how can I login to my django admin. I mistakenly turned my active to False as a superuser, now I can't login to my django admin. How can I get back superuser as active? I have tried login but couldn't access admin -
Error reversing django migrations with sql_safe_update mode set in MariaDB
I am running into issues when I try to reverse migrate one of the migrations in Django due to sql_safe_update mode is set in MariaDB. The exact sql statement it runs for reverse is: ALTER TABLE `user` DROP COLUMN `pin_code`; And the error that I get from django is: MySQLdb.OperationalError: (1175, 'You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column') Now my database is in inconsistent state because the column has been dropped and failed migration was not rolled back as MySQL DDL statements are not run in transaction. Now even with --fake it shows the same error. Is there a way to tell django to run migrations with sql_safe_update=0 only for duration of migrations? Note that I cannot turn off sql_safe_update globally as DB admins are adamant on not removing it globally. Also it is not entirely clear why DROP column requires a WHERE statement? -
Query sum with distant foreign key relations in Django
Let's say I have models like this: class Product(models.Model): ... class Item(models.Model): product = models.ForeignKey(Product, related_name="items") quantity = models.IntegerField() class Order(models.Model): item = models.ForeignKey(Item, related_name="orders") quantity = models.IntegerField() I now want to get a list of Product annotated with the field total_supply. "Total supply" is defined for each product as: (sum of all of a product's items' quantity) - (sum of quantity on all of the Order objects associated with one of the product's items.) Here is what I have tried: Product.objects.annotate(actual_supply=Sum("items__quantity") - Sum("items__orders__quantity")) I am getting unexpected results. How am I supposed to write such a query? Thank you -
How to define individual service name for each type of Opentelemetry auto instrumentation in a python application?
We are currently using Datadog for monitoring and observability in our application, and we have integrated OpenTelemetry for distributed tracing. We have encountered one main issue Span Separation: Currently, all the spans from our application are being exported to Datadog under a single service. However, we would like to separate them into different services based on the type of instrumentation used (e.g., Django, Elasticsearch, requests, etc.). Manage.py configure_opentelemetry() #Auto Instrumentation of Django, Psycopg2, Pymemcache, Elasticsearch, URLLib3, Requests DjangoInstrumentor().instrument(request_hook=fix_django_req) PymemcacheInstrumentor().instrument() RequestsInstrumentor().instrument() ElasticsearchInstrumentor().instrument() Psycopg2Instrumentor().instrument(enable_commenter=True, commenter_options={}) URLLib3Instrumentor().instrument() configure_opentelemetry method def configure_opentelemetry(): otlp_exporter = OTLPSpanExporter(endpoint=os.getenv("OTEL_COLLECTOR_URL"), insecure=True) # Set the global TracerProvider with the OTLP exporter trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: os.getenv("OTEL_SERVICE_NAME"), "env": os.getenv('OTEL_ENV')}))) # Create a BatchSpanProcessor and add the exporter to it span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) tracer = trace.get_tracer(__name__) Collector Config: receivers: otlp: protocols: grpc: http: processors: batch: # batch metrics before sending to reduce API usage send_batch_max_size: 100 send_batch_size: 10 timeout: 10s memory_limiter: # drop metrics if memory usage gets too high check_interval: 1s limit_percentage: 65 spike_limit_percentage: 20 resourcedetection: detectors: [env, gcp] timeout: 2s override: false transform: error_mode: ignore trace_statements: - context: span statements: - set(attributes["resource.name"], name) exporters: datadog: api: site: ${DD_SITE} key: ${DD_API_KEY} extensions: health_check: service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [memory_limiter, resourcedetection, … -
Django simple ModelForm not showing on page (I'm using class based-views), what could be the problem?
I'm trying to build a form to use it as a filter for my project search page, but the {{form}} shows nothing. Here is how everything is set up: The model I'm trying to use from models.py class Exemplar(models.Model): class Meta: verbose_name_plural = 'Exemplares' tipoDeExemplar = models.ForeignKey(TipoDeExemplar, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Tipo De Exemplar") numeroDeRegistro = models.CharField(max_length=255, verbose_name="Número Do Registro") especie = models.ForeignKey(Especie, on_delete=models.CASCADE, null=True) dataDoRegistro = models.DateField(blank=True, null=True, verbose_name="Data Do Registro") estadoDoExemplar = models.CharField(blank=True, null=True, max_length=255, verbose_name="Estado do Exemplar") tipoDeMaterial = models.CharField(blank=True, null=True, max_length=255, verbose_name="Tipo De Material") procedencia = models.CharField(blank=True, null=True, max_length=255, verbose_name="Procedência") remetente = models.CharField(blank=True, null=True, max_length=255, verbose_name="Remetente") armario = models.CharField(blank=True, null=True, max_length=255, verbose_name="Armário") gaveta = models.CharField(blank=True, null=True, max_length=255, verbose_name="Gaveta") complemento = models.CharField(blank=True, null=True, max_length=255, verbose_name="Complemento") amostraDeOrigem = models.CharFie fotoDoExemplar = models.ImageField(null=True, blank=True, upload_to='imagens/', verbose_name="Foto Do Exemplar") slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.numeroDeRegistro My forms.py file (very short) from django.forms import ModelForm from acervo.models import Exemplar class ExemplarForm(ModelForm): class Meta: model = Exemplar fields = '__all__' My view on views.py (seems to be working since I can open the page) class BuscaView(ListView): model = Exemplar template_name = 'busca.html' form_class = ExemplarForm Piece of the HTML template where I try to use the Django ModelForm <form action="" method="post"> … -
Django When I choose an account from the account tree using the check box
Django When I choose an account from the account tree using the check box, the account and its details are displayed on same template template acc.html template acc1.html view.py models.py -
OAUTH2 Django problems with client_secret
I was updating an old non documented project, database, users, etc.. Suddenly it came a problem, the client_secret_id is not hashed, if I edited in /o/applications then it become hashed. Is there a simple way to hash every client_secret_id other than manually do it one by one, application per application? I found the library, but I don't have any idea where is the salt, or how to include it -
How to get static files to work in Django | Favicon not getting loaded but appears when entering that directory
I'm having trouble trying to get my static files to work, I've already tried different answers for a long time and I'm getting confused what's the problem. I was trying to load my css with debug turned off, but I think its normal for the css not to appear since django doesn't load static files with debug turned off. My problem was when trying to put a favicon into my test website. I also think in the future I'll have complications with JS, etc.. main.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello, Django</title> <!-- load staticfiles--> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="shortcut icon" href="{% static "favicon.ico" %}}" type="image/png"> </head> <body> </body> </html> urls.py from django.urls import path from f1trackerapp import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ path("", views.f1trackerapp, name="f1trackerapp"), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] settings.py (stackoverflow doesn't let me post full settings.py code) ... from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
How do I make Django add the plural of category as categories instead of categorys
In my Django project I have a category tables however the plural is showing at categorys is there a way to force categories instead? I tried renaming the table but that did not work I also tried manually changing this by changing my model however I receive the same -
HTML does not recognize CSS file - Django
I recently started working on my first python + django project and I'm working on some visual things, but I noticed that the HTML isn't recognizing my CSS file. I follow the documentation about How to manage static files but nothing worked. So, this is my settings.py #app definition INSTALLED_APPS = [ #personalizacao #'grappelli', #Configuraçoes principais 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] #statics configs STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) In my HTML I have {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> And I can call the stuff that I have on the static/img folder with no problem So does anyone know what can it be? I don't know where to look anymore -
AWS EC2 Django Requests working from Public ipv4 address, but not Public ipv4 DNS address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty. /var/log/nginx/access.log shows that the api is receiving requests from both sites with no difference in the logs besides codes 200 29 for the successful request from the public ipv4, and codes 404 197 for the failed request from the public ipv4 DNS. It's also worth noting that the public ipv4 DNS serves the default nginx page on the base url while the public ipv4 shows resource not found. There are no relevant errors in /var/log/nginx/error.log. -
Why is Heroku not updating my Django app's code?
I have a Django blog deployed by Heroku, statics served with S3 Bucket. A few days ago I realised that my changes are not shown in the actual code when I inspect it with Chrome's Inspector tool. I pushed them to the git repo and to heroku master. This project is for my thesis, so it would be really important to resolve this problem. Thank you very much to spend your time helping me in advance. This is one of my latest changes: Added a paragraph to a django signup form that the user can view my Privacy Policy before signing up to my blog. I attached the code from PyCharm: {% extends 'default.html' %} {% block content %} <h1>Signup</h1> <form class="site-form" action="/accounts/signup/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Signup"> </form> <!-- Privacy Policy Link --> <p>By signing up, you agree to our <a href="https://www.termsfeed.com/live/d0e2bb42-feca-4abe-8051-afccfe402f6a">Privacy Policy</a>.</p> {% endblock %} The code from the actual website with Google's Inspector tool: <form class="site-form" action="/accounts/signup/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="1P17fSXi3R2ihBMd17GqUPmx2pIsL4c855BnGwrhTbenlx4sKQea1nJTuCK0Apei"> <label for="id_username">Username:</label><input type="text" name="username" maxlength="150" autofocus="" required="" id="id_username" data-siid="si_input_0"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span> <label for="id_email">Email:</label><input type="email" name="email" required="" id="id_email" data-siid="si_input_1"> <label for="id_password1">Password:</label><input type="password" name="password1" … -
AWS EC2 instance public ipv4 DNS address pointing to private ipv4 address instead of public ipv4 address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty, and accessing the api through the public ipv4 address http://xx.xxx.xx.xxx works properly, serving content when requested, with the base url showing Not Found. Accessing through the private ipv4 address does not respond. The problem is that when accessing through the public ipv4 DNS address, http://ec2-xx-xxx-xx-xxx.us-east-2.compute.amazonaws.com, where the x values match the public ipv4 address, the site only serves the default nginx page. Running nslookup on the DNS address returns the private ipv4 address. Why doesn't the DNS address point to the public ipv4 address? And why does it serve content at all if it points to the private ipv4 address which doesn't respond? Here are the configurations I used for nginx: Changed nginx.conf user to root, and created/linked django.conf in /etc/nginx/sites-available and /etc/nginx/sites-enabled: `server{ listen 80; Server_name [public … -
Onion site not found - Ubuntu 22.04.3 LTS / Unicorn / nginx / ufw / Dango .. on tor
Django web site does not happen to be accessible .. this is the simple demo django website. As this an onion V3, i increased the bucket size torrc HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 80 127.0.0.1:8080 Django settings ALLOWED_HOSTS = ['localhost', 'hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion'] Local tests are ok file /run/gunicorn.sock sudo systemctl status gunicorn curl --unix-socket /run/gunicorn.sock localhost Config Nginx sudo nano /etc/nginx/sites-available/sooshee server { listen 80; server_name hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/dj_test; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } cat /etc/nginx/nginx.conf server_names_hash_bucket_size 128; I just changed the bucket size to comply with onion length The only information i find, is this error message below sudo journalctl -u nginx кас 05 19:44:44 dave-MINI-S nginx[27984]: nginx: configuration file /etc/nginx/nginx.conf test failed кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Failed with result 'exit-code'. кас 05 19:44:44 dave-MINI-S systemd[1]: Failed to start A high performance web server and a reverse proxy server. кас 05 20:25:47 dave-MINI-S systemd[1]: Starting A high performance web server and a reverse proxy server... кас 05 20:25:47 dave-MINI-S nginx[28269]: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64 кас … -
Django cripsy form with a custom template for button
I have a need for a <button> element for my form submit instead of the layout helper Submit() input with Django and django-crispy-form. If I use {{ my_form|crispy }} I'm able to do this. However, with this method all of the other layout elements in the form are ignored. If I switch back to {% crispy my_form %} I get the layout back, but then my custom HTML button is ignored. Is there any way to have a custom HTML submit button while using the Layout helper? Note: If I add the HTML button below the crispy tag the button renders outside of the form, and I cannot iterate through the form fields in the template because my Layout in the Django form is very complex. -
React chat app messages don't have different className
I am making a chat app with django channels and react. I save the messages in state. When a new message is made I want it to have the className of the current user. The problem is that all messages have the className of the user reading them even if they were written from other. For example I am sending messages from 2 different browsers. The one is logged as first and the other as second. If first sends a message it will appear with a className of first. But for second this message will appear with a className of second chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <p ref={oneRef} id={currentUser[0]?.username} className={currentUser[0]?.username}>{data.message}</p>]) } } What can I do to solve this. -
Cannot reach Postgres Flexible Server from Web App
I have a Django app to deploy with a pipeline in azure DevOps and deploy To Azure cloud resources. The Django database is a Postgres Flexible Server in the same resource group. Also I have a virtual network resource in the Group. The pipeline install dependencies and then exec the tests from a command in a Makefile. In the tests step the Django app cannot reach the Database server, the name doesn't resolve to an IP, I try with the server Ip and get the same error. I didn't set any firewall rule neither private endpoints -
custom django signal receiver not being called wagtail code
We have a custom receiver connecting to the task_submitted signal in a project app. I have verified that the receiver is added to the dispatcher receivers Locally the receiver is invoked, however when deployed to our staging evnvironment in cloud foundry in a docker container the receiver is not invoked According to a log the self.receivers is None when invoking the dispatcher.send method ? -
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 -
passenger output: /bin/sh: line 0: exec: python: not found
I am trying to run django app I followed https://support.plesk.com/hc/en-us/articles/12377516625559. on Plesk Obsidian Version 18.0.41 Centos when logged in with root or my user python is aliased and responding I tried adding python to any basrc Any idea Thanks in advanced bellow is a detailed of the log level 7 App 174090 output: + '[' -x /usr/bin/id ']' App 174090 output: + '[' -z 10008 ']' App 174090 output: ++ /usr/bin/id -un App 174090 output: + USER=shlomi App 174090 output: + LOGNAME=shlomi App 174090 output: + MAIL=/var/spool/mail/shlomi App 174090 output: + '[' 10008 = 0 ']' App 174090 output: + pathmunge /usr/local/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: + pathmunge /usr/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: ++ /usr/bin/hostname App 174090 output: + HOSTNAME=localhost.localdomain App 174090 output: + HISTSIZE=1000 App 174090 output: + '[' '' = ignorespace ']' App 174090 output: + export HISTCONTROL=ignoredups App 174090 output: + HISTCONTROL=ignoredups App 174090 output: + export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL App 174090 output: + '[' 10008 -gt 199 ']' App 174090 output: ++ /usr/bin/id -gn App 174090 output: ++ /usr/bin/id -un App 174090 output: + '[' psacln = shlomi … -
Is it normal that Django ORM makes a DB call on every object in a List View?
I'm facing a problem of extra DB calls to retrieve object's data. I have a model: class Post(models.Model): profile = models.ForeignKey(Profile, related_name="posts", on_delete=CASCADE) project = models.ForeignKey(Project, related_name="posts", on_delete=CASCADE) body = models.TextField(verbose_name="Content", max_length=1300) liked_by = models.ManyToManyField(Profile, related_name="post_likes", blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="Date published") date_modified = models.DateTimeField(auto_now=True, verbose_name="Date modified") is_active = models.BooleanField(verbose_name="Active", default=True) tags = TaggableManager(blank=True, related_name="posts") I am calling a View to list all Post objects (currently, there are 4) but getting 4 extra queries to posts_post for each entity. Is that normal behaviour to make an individual DB call on each entity in DB (not related entities but the root entities). My query : all_posts = ( Post.objects .select_related("profile__specialization", "project") .prefetch_related( "tags", Prefetch( "liked_by", queryset=Profile.objects.select_related("specialization").only( "id", "username", "first_name", "last_name", "photo", "specialization" ) ) ) .annotate( comments_count=Count("comments", distinct=True), likes_count=Count("liked_by", distinct=True) ) .defer("body") .order_by("-date_published") ) My query list as per DjDT: -
ModuleNotFoundError: No module named 'storages'
I no idea why this error kept occur in my terminal my current django version, 4.2.3 python version, 3.10.6 and my virtual environment is on, and I did downloaded these pip pip install boto3 pip install django-storages and my settings.py INSTALLED_APPS=[ ... 'storages', ] and DEFAULT_FILE_STORAGE='storages.backends.s3boto3.S3Boto3Storage' ok then, I try to run my server, python manage.py runserver it came out these error ** Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python latest\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python latest\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python latest\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
Django reloading a page without loosing user inputs in a form
I am working on translating my Project. I implemented a language Switch in my basetemplate: {% load i18n %} {% load language_tags %} <!-- imports all tags from templatetags/language_tags.py (see below) --> ... <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% translate 'Language' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as langs %} {% for lang in langs %} <li><a class="dropdown-item" href="{% translate_url lang.code %}">{{lang.name_local}}</a></li> {% endfor %} </ul> </li> </ul> </div> ... The important part here ist the href={% translate_url lang.code %} It is a custom template tag (see templatetags/language_tags.py) in my projetc that i have from here: https://stackoverflow.com/a/17351858/21828018 It's usage ({% translate_url de %}) is to give back the url you are visiting in the given language e.g. if you are visiting en/product/product_id and you use {% translate_url de %} it returns de/product/product_id. In combination with i18n_patterns the translation works so far. templatetags/language_tags.py: """language_tags.py""" from django import template from django.urls import reverse, resolve from django.utils import translation from django.conf import settings register = template.Library() class TranslatedURL(template.Node): """gets current path and creates new url with passed … -
Django .aggregate() on prefetched element not filtering by date
I have a queryset that I am prefetching entries between a range of dates, I am trying to annotate the totals of the prefetched elements into the outer element. When I call .annotate() on the outer element the filtered date ranges do not pass through. How do I fix this? GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date)), ).filter(account_identifier='1011.00').annotate(Sum('general_ledger__credit_amount')) The annotated value grabs all general ledger entries from the start of time. -
Master Ref ID is not working as expected in Details Table
I am getting this error message: {"status":400,"message":{"reason_items":[{"master_ref_id":["This field is required."]}]}} master_ref_id isn't supposed to be passed in postman(Details Table gets connected to Masters Table by master_ref_id which is autogenerated). But When I manually give master_ref_id, I get an obvious error: TypeError at /chargeback-reason/ django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() got multiple values for keyword argument 'master_ref_id' This is the data I am passing in postman for 'POST' request. { "name": "name3", "action_id": 1, "reason_items": [ { "attachement_format_id": 1, } ] } serializer.py file class ChargeBackReasonDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = ChargeBackReasonDetails fields = '__all__' class ChargeBackReasonSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) reason_items = ChargeBackReasonDetailsSerializer(many=True) class Meta: model = ChargeBackReason fields = '__all__' def create(self, validated_data): item_row = validated_data.pop('reason_items') reason = ChargeBackReason.objects.create(**validated_data) for item in item_row: ChargeBackReasonDetails.objects.create(**item, master_ref_id = reason) return reason views.py file def create(self, request): with transaction.atomic(): data = dict(request.data) data['created_by'] = request.user.id data['updated_by'] = request.user.id data['updated_date_time'] = datetime.now(pytz.timezone(TIME_ZONE)) for item in data['reason_items']: item.update({'created_by':request.user.id,'updated_by':request.user.id,'updated_date_time':datetime.now(pytz.timezone(TIME_ZONE))}) serializer = ChargeBackReasonSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({STATUS: RECORD_CREATED}, status=status.HTTP_201_CREATED) else: return Response({STATUS: status.HTTP_400_BAD_REQUEST, MESSAGE: serializer.errors}, status=status.HTTP_400_BAD_REQUEST) models.py file class ChargeBackReason(models.Model): action_id = models.ForeignKey(ChargeBackAction, verbose_name="action_id", on_delete=models.PROTECT) name = models.CharField(max_length=100,verbose_name='name') class ChargeBackReasonDetails(models.Model): master_ref_id = models.ForeignKey(ChargeBackReason, verbose_name="Master Ref Id",related_name="reason_items",on_delete=models.PROTECT) attachement_format_id = models.ForeignKey(AllMaster,verbose_name="Attachement Format",on_delete=models.PROTECT))