Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Iterate response value in combobox using inline jquery ? -Django
I have an object named data2 contains multiple data that I'm rendering from views.py to my HTML template. {% for item in data2 %} <tr> <td><input type="text" name="from" class="form-control input_data" value="{{item.from_age}}"></td> <td><input type="text" name="to" class="form-control input_data" value="{{item.to_age}}"></td> <td id ="gender_select"> <script>$(function() {$('#gender_select :input').each(function() { $("#gender option[data-value='" + '{{item.gender}}' +"']").attr("selected","selected"); });});</script> <select name="gender" id="gender" class="form-control input_data" > <option data-value="select" >Select</option> <option data-value="male" >Male</option> <option data-value="female" >Female</option> </select> </td> <td><a href='' class='remove'><span class=''></span></a></td> </tr> {% endfor %} In {{item.gender}}, on the first iteration, I have value 'Male' and on the second iteration, I have value "Female" so it should be automatically select the value but after executing the above code, I'm facing an error $ is not defined also can't see the values. Please let me know where i'm wrong ? -
Can I create a new PostgreSQL schema and make migrations with Django at runtime?
I am trying to build a multi-tenant application in Django where each tenant will have a PostgreSQL schema and a different subdomain (So shared Database with isolated schema). For every request that comes to the api I have a Django middleware that sets the PostgreSQL schema. Now I want to know what happens if I have my Django App running in production and I want to add a new schema and run the makemigrations command. Is it OK to do that at runtime, or is there a better way to do this? -
get() returned more than one Health -- it returned 33233! Django
I am Trying to get Single object data based on id i am using class based view and Restframework I have also Try Different Approaches but not Work views.py class HealthDetailView(viewsets.GenericViewSet,mixins.UpdateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin): serializer_class=HealthSerializer queryset=Health.objects.all() permission_classes =[] authentication_classes=[] lookup_field='id' def get(self,request,id): serializer=HealthSerializer(Health.objects.filter(id=id)) return Response(serializer.data) serializers.py class HealthSerializer(serializers.ModelSerializer): class Meta: model = Health fields = '__all__' Url Pattern urlpatterns +=[ path('health-detail/<int:id>/',HealthDetailView.as_view({ 'get': 'retrieve'}),name='health-detail') ] Error -
How to get the Operating System of the user using Django?
I followed this guide trying to get user agent from request specifically the Operating System Obviously I cannot use the normal way of getting the operating system which is using the os module with python but that won't work because the operating system will be the one hosting the server TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPALTES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'myproject.myapp.context_processors.user_agent', ], }, }, ] cannot do that. it claims that I don't have a myproject.myapp module -
DRF, update or create in post request with multiple fields lookup
I have a DRF API with a model of months, I need to provide a way to make one endpoint for creating or updating objects (so either post or patch endpoint). I tried taking example from these two answers: Multiple Lookup fields answer overriding view's create method for update or create The second answer is using the view and not the serializer and that's a behaviour I would rather keep. My code so far: class MultipleFieldLookupMixin: def get_object(self): queryset = self.get_queryset() queryset = self.filter_queryset(queryset) filter = {} for field in self.lookup_fields: if self.kwargs.get(field, None): filter['field'] = self.kwargs['field'] obj = get_object_or_404(queryset, **filter) self.check_object_permissions(self.request, obj) return obj class MonthsViewSet(ModelViewSet, MultipleFieldLookupMixin): authentication_classes = (TokenAuthentication,) def get_queryset(self): query_set = Month.objects.all() return query_set serializer_class = MonthSerializer lookup_fields = ['month', 'year', 'farm'] def create(self, request, *args, **kwargs): kwarg_field: str = self.lookup_url_kwarg or self.lookup_fields self.kwargs[kwarg_field] = request.data[self.lookup_fields] try: return self.update(request, *args, **kwargs) except Month.DoesNotExist: return super().create(request, *args, **kwargs) serializer: class MonthSerializer(serializers.ModelSerializer): class Meta: model = Month fields = '__all__' So now trying to create or update a field raises the following error: self.kwargs[kwarg_field] = request.data[self.lookup_fields] TypeError: unhashable type: 'list' -
Django UserCreationForm not saving
from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def home(request): return render(request, 'myapp/index.html') def registration(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save(Commit = False) form.cleaned_data.get('username') form.cleaned_data.get('password1') form.cleaned_data.get('password2') form.save() dict = {'form':form} return render(request, 'myapp/registration.html', context = dict) -
How to get field name instead of foreign id in django
In my django app, i have four model tables linked using foreign keys, the problem is, when i make a query for any model table, the fields that are linked through foreign keys are returned as id's instead of the name. My way does not work. My customers models.py file 1st model class Customer(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=20, unique=True) email = models.EmailField(max_length=255, unique=True, blank=True) image = models.ImageField(default='default.png', upload_to='customer_photos/%Y/%m/%d/') data_added = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.name 2nd model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_ship_address") description = models.TextField(blank=True) frequent_customer = models.BooleanField(default=False) address = models.CharField(max_length=50, blank=True) zip_code = models.CharField(max_length=12, blank=True) location = models.CharField(max_length=255) def __str__(self): return self.customer.name 3rd model - PaymentInvoice class paymentInvoice(models.Model): shipping_address_owner = models.ForeignKey( ShippingAddress, on_delete=models.CASCADE, related_name="customer_invoice") product = models.ManyToManyField( Product, related_name='product_invoice') mode = models.CharField(max_length=20, choices=paymentMode.choices, default=paymentMode.MPESA) date = models.DateField(default=datetime.now) invoice_id = models.CharField( max_length=50, unique=True, default=increment_invoice_number) quantity = models.PositiveSmallIntegerField() status = models.CharField( max_length=20, choices=paymentStatus.choices, default=paymentStatus.PENDING) payment_made = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.shipping_address_owner.customer.name My Products models.py file class Product(models.Model): slug = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200) available = models.BooleanField(default=True) description = models.TextField(blank=True) image = models.ImageField(default='default_product.jpg', upload_to='product_photos') category = models.CharField(max_length=200) qty_amount = models.CharField( max_length=20, choices=Qty_Choices, default='250ml') price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name My PaymentInvoice views.py file … -
Django csrf_token error, while I wrote it
Django csrf_token error, while I wrote it in my HTML file, but why does this error message poped up when I wrote that csrf_token? <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'f/ask/ask.css' %}"> <title>BareTalk</title> </head> <body> {% block content %} <div id="wrapper"> <form method="POST" action="">{% csrf_token %} {{ form }} <!-- TODO: input submit Reg() function javascript --> <button name="final" id="final">Ask</button> </div> </form> </div> {% endblock %} </body> <script src="{% static 'f/ask/ask.js' %}"></script> </html> -
Restrict number of Foreign keys relations in Django
Is it possible to have max number of relations by foreign key in django? For example, I want to have no more than 10 posts made by one user. I init the model class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) where should I add this check? Or it's not possible and I should make it in view? -
NameError: name 'JSONResponseMixin' is not defined
I am getting this error but I don't get it why? I am following the Django documents and part of the code which get error is from https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/ (the last code in the link) The error: /views.py", line 11, in <module> class ProgramListView(ListView, JSONResponseMixin, SingleObjectTemplateResponseMixin): NameError: name 'JSONResponseMixin' is not defined My Code in views.py: from programs.models import Program from django.views.generic import ListView, DetailView from django.http import JsonResponse from django.views.generic.detail import SingleObjectTemplateResponseMixin from django.views.generic.detail import BaseDetailView class ProgramListView(ListView, JSONResponseMixin, SingleObjectTemplateResponseMixin): model = Program template_name = 'programs/program_list.html' context_object_name = 'programs' paginate_by = 6 paginate_orphans = 3 def get_queryset(self): url_parameter = self.request.GET.get('q') # if self.request.method == 'GET' and self.request.is_ajax(): if self.request.method == 'GET': queryset = Program.objects.filter(degree = url_parameter) return queryset if self.request.method == 'GET' and url_parameter is None: queryset = Program.objects.all() return queryset def render_to_response(self, context, url_parameter='BSc'): # Look for a 'format=json' GET argument # if self.request.GET.get('format') == 'json': # if self.request.is_ajax(): if url_parameter=='BSc': return self.render_to_json_response(context) else: return super().render_to_response(context) -
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve
my docker file version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres my settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } when I run sudo docker-compose build it shows django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve where I did mistake ? -
How to add custom 'Error 404' page in my Django Web App
I am making a web app in which if a person enters a wrong url it leads him/her to a Custom Error 404 HTML page. How can we implement it in Django. For Example: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.Home, name='Home'), path('Login', views.Login, name='Login'), path('Register', views.Register, name='Register'), path('Logout', views.Logout, name='Logout'), ] Suppose a person enters http://127.0.0.1:8000/Chat/Logooiuut Then he should go to my Custom Designed Error Page Any idea on how to implement it? -
Import M2M Empty values imported
Using Widget Many to many when importing the result is empty. Tags do exists in the original model. See Image. import result Excel imported | provider | tag | provider_tag_id | |-----------|-----------------|-----------------| | Lionsgate | Planes, Top | | | FOX | Houses, Low | | | Dorcel | something, else | | Model where the m2m is pointing class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name Model where the m2m relationship is class ProviderTag(models.Model): provider_tag_id = models.AutoField(primary_key=True) provider = models.ForeignKey(Provider, on_delete=models.DO_NOTHING) tags = models.ManyToManyField(Tag) Resource to import class ProviderTagResource(resources.ModelResource): provider = fields.Field( column_name='provider', attribute='provider', widget=ForeignKeyWidget(Provider, 'name') ) tags = fields.Field( column_name='tags', attribute='tags', widget=ManyToManyWidget(Tag, separator=',', field='name') ) class Meta(): model = ProviderTag fields = ('provider', 'tags', 'provider_tag_id',) import_id_fields = ('provider_tag_id',) Admin.py class ProviderTagAdmin(ImportExportModelAdmin): list_display = ('provider', 'get_tags', 'provider_tag_id') search_fields = ['provider',] resource_class = ProviderTagResource def get_tags(self, obj): print(obj.tags) return ", ".join([str(p) for p in obj.tags.all()]) admin.site.register(ProviderTag, ProviderTagAdmin) -
fe_sendauth: no password supplied | Windows virtual env
I am currently trying to connect my PostgreSQL database in my computer to a Django project. I have read some other post on the same topic but I cannot figure out what it is. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':os.environ.get('DB_NAME'), 'USER':os.environ.get('DB_USER'), 'PASSWORD':os.environ.get('DB_PASSWORD'), 'HOST':os.environ.get('DB_HOST'), } } .env export DB_NAME=test export DB_USER=postgres export DB_PASSWORD=password export DB_HOST=localhost First, I open the virtual environment pipenv shell and then do python manage.py runserver, however I get the following error: django.db.utils.OperationalError: fe_sendauth: no password supplied. It was working perfectly before creating .env and changing the values over there, also, I have installed the most recent version of psycopg2. -
How to append HTML rows when it returns Multiple Objects in Django?
While inserting a data, I added a button <button class="btn-insert-data">Add New Row</button> that have the following Jquery function that is inserting data properly to database using ajax. $(function() { $(".btn-insert-data").click(function(){ var html_data = "<tr><td><input type='text' name='from' class='form-control input_data'</td><td><input type='text' name='to' class='form-control input_data'></td><td><select name='gender' class='form-control input_data'><option value='select' selected>Select</option><option value='male'>Male</option><option value='female'>Female</option></select></td><td><a href='' class='remove'><span class=''></span></a></td></tr>"; $(".table tbody").append(html_data); }); how to get the multiple rows if I have multiple values from database to show the values in edit page ? Currently it's just showing me an error get() returned more than one PoliceDepartment -- it returned 2! when my html code is the following, <tbody> {% for item in data2 %} <td><input type="text" name="from" class="form-control input_data" value="{{item.from_age}}"></td> <td><input type="text" name="to" class="form-control input_data" value="{{item.to_age}}"></td> <td><select name="gender" class="form-control input_data"> <option value="" selected>Select</option> <option value="male">Male</option> <option value="female">Female</option> </select></td> <td><a href='' class='remove'><span class=''></span></a></td> {% endfor %} </tbody> Please let me know the solution! -
I'm using ajax to set up a view of uploaded data, but it works in first item only
I have to set up the user should be able to view the contact info of customer, For that I'm using ajax. the code is working but the problem is the ajax is only working in the first item, other buttons are not working what is the reason another issue is when i hit the button again it showing data agin and agin how to control it how to solve these two issues views.py def contact_details(request): property_details = Property.objects.all() seraializer = PropertySerializer(property_details, many=True) data = seraializer.data return JsonResponse(data, safe=False ) HTML page(including ajax) {% if accomodations %} {% for accomodation in accomodations %} <div class="row"> <div class="col-sm-2 col-md-2"></div> <div class="col-sm-4 col-md-4"> <img src="{{accomodation.images.url}}" class="img-responsive" style="width:100%"> </div> <div class="col-sm-5 col-md-5"> <div class="caption"> <h3>{{ accomodation.headline }}</h3> <div> {{ accomodation.city }} </div> <div> {{ accomodation.location }} </div> <div> {{ accomodation.facilites }} </div> <div> {{ accomodation.rent }} </div> <div> {{ accomodation.owner }} </div> <div> {{ accomodation.id }} </div> <button id="request-btn" name="property_id" class="btn btn-primary">Contact info:</button> </form> <div id=response></div> </div> </div> </div> <hr> {% endfor %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#request-btn").click(function(){ $.ajax({ url: "{% URL 'contact_details' %}" , type: "GET", dataType:"json", success: function(result){ $.each(result, function() { html = "Email:" +this.email + "<br>" +"Mobile:" + this.mobile … -
how to create private groups for users in django
let us magnify my problem with an example i am the user and i signup for website. then i add some more 4-5 friends and now i want to make a group so that i am the admin of that groups ( the permissions allowed for group admin is adding users , removing users , deleting group ) but i also want that if any other user of the site who is not my friend is interested in my group but when he clicks the join button he should be prompted for the password of the group in order to join the group or else i should be able to create a one-time use link so that whom so ever i send the link he/she can join the group. **i am sorry to say this but i don't think most of the platform users can answer this question because it is tricky one & i am noob. ** -
why codes don't uploaded in my Github repository? [duplicate]
I have one Github repository and in my local computer have One project named DjangoReact inside this folder, I have to subfolder Backend and Frontend, so everything inside backend uploaded into my repository but inside the frontend doesn't upload to Github. I don't know why? please help me, thank you. -
Custom Exceptions with Django Rest Framework
I want to create custom exceptions in DRF. As the DRF documentation states that i can do that by creating a user defined class and inheriting from APIException. That works well but the issue is my application require me to send some type of custom codes along with the HTTP status codes. For example, when an error occurred while creating a ProductCatalog it should return something like this along with HTTP status code. {"code": 4026, "message": "Unable to create catalog"} Such thing is required because although my API worked correctly so the http status code will be 200 but there were some business logic that was not fulfilled hence i need to return some sort of custom code and message to let the client application handle it accordingly. Any kind of help will be appreciated. -
Count the leave days and display them in django admin model
I am learning django or a month now. I created a model called "Leave" to mark employees leave. Then I created a model called "Salarie".In this I need to create a field like "Total_Leave" which will show an employees leave count in a month.( In january 2020 how many leave a particular employee took) I tried to do it like this and tried some coding but nothing worked. @property def Total_Leave(self): return self. Can anyone explain me how to do that please? Models.py class Leave(models.Model): Leave_ID = models.CharField(max_length=5, primary_key=True,default=" ") Employee_Name = models.ForeignKey('Employee_Detail',models.DO_NOTHING) Dept_Name = models.ForeignKey('Department', models.DO_NOTHING) l = ( ("Paid","Paid"),("Non-Paid","Non-Paid") ) Leave_Type = models.CharField(max_length=10, choices= l, default="Non-Paid") m = ( ("January","January"),("February","February"),("March","March"),("April","April"),("May","May"),("June","June"),("July","July"),("August","August"),("September","September"),("October","October"),("November","November"),("December","december") ) Month = models.CharField(max_length=10, choices= m) Year = models.IntegerField(max_length=4) Start_Date = models.DateField() End_Date = models.DateField(null=True, blank = True) Reason = models.CharField(max_length=200) s = ( ("Accepted","Accepted"),("Pending","Pending"),("Canceled","Canceled") ) Status = models.CharField(max_length=10, choices= s, default="Pending") def __str__(self): return str(self.Employee_Name) class Salarie(models.Model): Salarie_ID = models.CharField(max_length=5,primary_key=True,default=" ") Employee_Name = models.ForeignKey('Employee_Detail', models.DO_NOTHING) Dept_Name = models.ForeignKey('Department', models.DO_NOTHING) Basic_Salary = models.IntegerField(default=0) Extra_Hours = models.IntegerField(default=0) @property def Extra_Payment(self): return self.Extra_Hours * 350 Bonus = models.IntegerField(default=0) @property def Total_Payment(self): return self.Extra_Payment + self.Basic_Salary + self.Bonus m = ( ("January","January"),("February","February"),("March","March"),("April","April"),("May","May"),("June","June"),("July","July"),("August","August"),("September","September"),("October","October"),("November","November"),("December","december") ) Month = models.CharField(max_length=10, choices= m) Year = models.IntegerField(max_length=4) … -
Fetch Data from REST API sends two requests and can't authenticate
I'm trying to fetch data in my React app from an Django server with Django Rest Framework, I'm using the built in token authentication. componentDidMount() { let headers = { "content-type": "application/json", "authorization": "Token <token is here>" }; fetch('http://localhost:8000/api/stats/', { headers: headers, }) .then(res => res.json()) .then((data) => { this.setState({ games: data }) }) .catch(console.log) } Inspecting the page in Chrome reveals this This looks like two separate requests but I'm not sure. The requests that has status (failed) has the headers I provided in React with in it. This request seems to have failed completely, it did not even reach the server. The other request that has the status 401 doesn't have the headers I provided. The request did however get a response from the server. Anyone have an idea what's wrong? -
Unable to force strict mode for mysql tables in Django project
I can't seem to get rid of this error message when I run python manage.py migrate: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.0/ref/databases/#mysql-sql-mode In the database section of my settings.py file, I added the following code: 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", Then I ran the migrate command again but the same error keeps showing up. Any help would be appreciated. -
Django subtraction function giving an error
I have two models Product and Stock. The stock model holds the stock of each product and I have a form that lets the user choose the product and amount he/she wishes to purchase then the amount entered by the customer is subtracted from stock model quantity. Now I want the function to only subtract when the status is 'Shipped'. I tried adding if product.status == 'Shipped' statement , but I'm getting this error "local variable 'product' referenced before assignment". models.py class Product(models.Model): product_choices = (('Product1', 'Product1'), ('Product2', 'Product2'), ('Product3','Product3'), ('Product4','Product4'), ) product = models.CharField(max_length = 100, choices = product_choices) amount = models.IntegerField(max_length = 100) status_choices = (('Overdue', 'Overdue'), ('Scheduled', 'Scheduled'), ('Processing', 'Processing'), ('Shipped','Shipped'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") class Stock(models.Model): stockId = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100) quantity = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.product_name views.py def create_order(request): form = OrderForm(request.POST or None, request.FILES or None,initial=initial_date, user=request.user) if request.method == 'POST': if form.is_valid(): amount = form.cleaned_data.get('amount') product = form.cleaned_data.get('product') Stock.objects.filter(product_name=product).update(quantity=F('quantity') - amount*30) product = form.save(commit = False) product.user = request.user; product.save() form = OrderForm(user=request.user) return redirect('/orderlist') context = {'form':form} html_form = render_to_string('order_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) -
DRF - Unable to serialize an OrderedDict object containing Object Ids
Background I am using djongo to interface with a MongoDB database. My models make use of an auto-generated _id field of type djongo.models.ObjectIdField and my APIViews are presently executing the .get() and .filter() methods on my model querysets to perform database transactions. The Problem When serializing the aforementioned QuerySet results, my serializers successfully do so and in return yield the serialized data that I can then send across in a Response object through my APIViews. However, I have recently transitioned to executing raw NoSQL queries in place of the .get() and .filter() methods mentioned above. The following page on djongo, under section Using Pymongo commands, details how to use pymongo commands to be able to perform these raw queries. I am able to exploit this fact and have successfully refactored part of my codebase to experiment with these commands. Unfortunately, my existing model serializers will serialize all the data these pymongo commands return except for the _id field of each returned model. Most importantly, .filter(...) would return a QuerySet object, which my serializers handle perfectly fine. Now, something along the lines of .mongo_find(...), which is instead executed on an instance of the DjongoManager, would return an OrderedDict object whose _id … -
Serialize a single Related Field in Django
In my Django application I am getting data from seriallizer like the following: { "id": 98, "flows": [ { "id": 99, "asked_quantity": 14, "alloted_quantity": 14, "flow": 1, "kit": 1 #this } ], "transaction_no": 2317, "dispatch_date": "2020-07-27T04:42:46.356000Z", "is_delivered": false, "model": "Rent", "driver_name": "__________", "driver_number": "__________", "lr_number": 0, "vehicle_number": "__________", "freight_charges": 0, "vehicle_type": "Part Load", "expected_delivery": "2020-07-27T04:42:46.356000Z", "remarks": "0", "send_from_warehouse": 1, #this "sales_order": 98, "transport_by": 4, "owner": 2 }, Where Flows is a manytomany connected field, I just want to Expand the kit from flows and send_from_warehouse but when I increase the depth all the related fields gets expanded. Here's how I tried doing this : class KSerializer(serializers.ModelSerializer): class Meta: model = Kit fields = "__all__" class WSerializer(serializers.ModelSerializer): class Meta: model = Warehouse fields = "__all__" class AFSerializer(serializers.ModelSerializer): kit = KSerializer(many=True) class Meta: model = AllotmentFlow fields = "__all__" class AReportSerializer(serializers.ModelSerializer): flows = AFSerializer(many=True) send_from_warehouse = serializers.RelatedField(source='warehouse.pk', read_only=True) class Meta: model = Allotment fields = "__all__" But I got the error that 'kitsis not serializable andsend_from_warehouse` vanishes from the JSON. Please explain why did that happen and what's the right way