Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why it show bad request Bad Request: /updateuser/id/
I am trying to update the User details.I have separate MyUser and Profile models join with a Foreign key relation.I have written a nested serializer UsersProfileSerializer.I want to update both MyUser and Profile details together. When I hit submit then in network I see bad request error.May be I am not passing the correct format of response according to my django rest api.When I tried to print request.POST, it show like this in browser console:(if I want to change address then) { address: Array(1), user: {…}} address: ['Not a valid string.'] user: {username: Array(1), bio: Array(1)} [[Prototype]]:Object Please take a look and suggest me my fault.Thanks in advance. My Models are: class MyUser(AbstractUser): bio = models.CharField(max_length=500, blank=True) is_younger = models.BooleanField(default=False) class Profile(models.Model): genders = [ ("M", "Male"), ("F", "Female"), ] user = models.ForeignKey(MyUser, on_delete=models.CASCADE,related_name="profile") age = models.CharField(max_length=2,blank=True,null=True) gender = models.CharField(max_length=1, choices=genders) contact = models.CharField(max_length=12,blank=True, help_text='Contact phonenumber') address = models.CharField(max_length=100, blank=True) The Serializers are: class ListUsersSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['id', 'username', 'email','bio', 'is_younger'] class UsersProfileSerializer(serializers.ModelSerializer): user = ListUsersSerializer() class Meta: model = Profile fields = ['id','age','gender','contact','address','user'] def update(self, instance, validated_data): user_data = validated_data.pop('user') if user_data is not None: instance.user.id = user_data['id'] instance.user.username = user_data['username'] instance.user.email = user_data['email'] … -
How to change initial value of field if clean_{FOO} is invalid?
I have a ModelForm with a clean function for a field. I want to alter the initial value for the field based on some conditional logic in the field: class MyForm(forms.ModelForm): text_field_1 = forms.CharField() def clean_text_field_1(self): data = self.cleaned_data['text_field_1'] if data == 'Hello': self.fields['text_field_1'].initial = 'Goodbye' return ValidationError('Don't say Hello', code='invalid_input') return data However, I can't access the self.fields property of the form from the clean function (it makes no changes). How do I do this? -
How can I fix/ workaround this KeyError when I try to extract from a json via my python API request?
I have been trying to seed a django DB with some covid data from an api and get a KeyError for a particular data type - in the source it is a floating_timstamp ("lab_report_date" : "2014-10-13T00:00:00.000"). (edit: not sure if the type is relevant, but trying to be comprehensive here). I tried doing a more simple API request in python but get the same keyError. Below is my code and the error message. import requests response = requests.get("https://data.cityofchicago.org/resource/naz8-j4nc.json") print(response.json()) The output looks like this: [ { "cases_age_0_17": "1", "cases_age_18_29": "1", "cases_age_30_39": "0", "cases_age_40_49": "1", "cases_age_50_59": "0", "cases_age_60_69": "0", "cases_age_70_79": "1", "cases_age_80_": "0", "cases_age_unknown": "0", "cases_asian_non_latinx": "1", "cases_black_non_latinx": "0", "cases_female": "1", "cases_latinx": "1", "cases_male": "3", "cases_other_non_latinx": "0", "cases_total": "4", "cases_unknown_gender": "0", "cases_unknown_race_eth": "1", "cases_white_non_latinx": "1", "deaths_0_17_yrs": "0", "deaths_18_29_yrs": "0", "deaths_30_39_yrs": "0", "deaths_40_49_yrs": "0", show more (open the raw output data in a text editor) ... "hospitalizations_unknown_gender": "3", "hospitalizations_unknown_race_ethnicity": "16", "hospitalizations_white_non_latinx": "135" } ] So far so good, but if I try to extract the problem key, i get the KeyError: report_date = [] for i in response.json(): ls = i['lab_report_date'] report_date.append(ls) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /var/folders/h3/5wlbmz0s3jb978hyhtvf9f4h0000gn/T/ipykernel_2163/2095152945.py in <module> 1 report_date = [] 2 for i in response.json(): ----> … -
Django update index after adding records to db programmatically
I added a number of records to a Django db table (machina forums) directly via a script (ie: I did not use the site admin interface). The structure seemed fairly straightforward with no foreign keys in other tables. However the resulting displays are uneven. In a forum index display all of the children forums display under a category. However if I go into the category, only forums added via the admin interface are visible. There does not appear to be any difference in the db records between those that were added programmatically and those added via the admin interface. I am guessing the issue has to do with indexes on the table. However when I use a GUI to view the db all of the indexes show "result set is empty." Any ideas about what is causing the problem and if it is index related, how do I update the index? -
How to implement an external python code to a Django web server?
as from the title, I am trying to implement an external python code to a Django web server. I am quite new to programming so any hints will be surely helpful. Long story short: I am trying to set up a form where the user have to insert an aminoacidic sequence. This sequence should pass to my python script, that is able to compare it with all the sequences already present in the database and gives as a result the most similar ones. My problem is that I am not able to let my form and my script talk each others. I have followed the Django documentation here https://docs.djangoproject.com/en/3.2/topics/forms/ but this did't helped too much. Also roaming online and browse already asked questions here was unfruitful. Please find here below the files: BLAST_page.html (tried both, commented and uncommented) {% extends "base_generic.html" %} {% block content %} <div class="container-fluid" style="text-align: center;" ></div> <form method="post" action= {% url 'BLAST-process' %}> {% csrf_token %} {{ blast }} <label for="sequence">Type or paste your sequence in the box below</label><br><br> <input type="text" id="sequence" class="input_text" name="sequence" value="{{ sequence }}" style="width:600px; height:200px;"><br><br> <input type="submit" value="Submit"> </form> </div> {% endblock %} <!-- <div class="container-fluid" style="text-align: center;" > <form method="POST" … -
How can I pre-process a file's contents being saved into a FileField in Django?
There's a .csv being saved into a FileField in Django 2.2. Before it gets saved, I want to delete some rows in it. This is what I have so far: # A Custom File Field that will modify the file contents before saving it class CustomFileField(models.FileField): # The method that gets called before the save happens def pre_save(self, model_instance, add): file_field = super().pre_save(model_instance, add) file_field = self.update_file_contents(file_field) return file_field def update_file_contents(self, file_field): # NEED TO SOMEHOW UPDATE THE CONTENTS OF # THE file_field HERE BEFORE RETURNING IT return file_field # The model that uses this Custom File Field class MyModel(models.Model): my_csv_file = CustomFileField(upload_to='results/%Y/%m/%d/') I'm not quite sure what my update_file_contents method needs to do to update the contents of the file. Has the file been saved to the filesystem by the time my method is called? Or is it still in memory? Or should I forget making a custom FileField, and simply override my MyModel's save method, so that after the file is saved to the filesystem, I open it again, and modify it like I would any file? -
Trouble trying to get size of Celery queue using redis-cli (for a Django app)
I'm using Django==2.2.24 and celery[redis]==4.4.7. I want to get the length of my celery queues, so that I can use this information for autoscaling purposes in AWS EC2. I found the following piece of documentation: https://docs.celeryproject.org/en/v4.4.7/userguide/monitoring.html#redis Redis If you’re using Redis as the broker, you can monitor the Celery cluster using the redis-cli command to list lengths of queues. Inspecting queues Finding the number of tasks in a queue: $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME The default queue is named celery. To get all available queues, invoke: $ redis-cli -h HOST -p PORT -n DATABASE_NUMBER keys \* Note Queue keys only exists when there are tasks in them, so if a key doesn’t exist it simply means there are no messages in that queue. This is because in Redis a list with no elements in it is automatically removed, and hence it won’t show up in the keys command output, and llen for that list returns 0. Also, if you’re using Redis for other purposes, the output of the keys command will include unrelated values stored in the database. The recommended way around this is to use a dedicated DATABASE_NUMBER for Celery, you can also use … -
how can i upload any doc file to my my model from user side and download it,in django?
here I am trying to make a form where users can upload their location and their cv and it should be saved on my Django model. After that, I want to download the same file. for uploading, I am trying this my model looks like this. models.py class canDetails(models.Model): canEmail=models.ForeignKey(candidate,on_delete=models.CASCADE) location=models.CharField("location ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/canDetails/",default="") def __str__(self): return self.canEmail in my html <form method="POST" class="form mb-5 mx-1 mx-md-4 mt-4" action="{% url 'canDetails' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="element"> <input type="text" name="location" placeholder="Location" id="location" required /><br> </div> <div class="element"> <input type="text" name="role" placeholder="Role/Stream" id="role" required /><br> </div> <div class="element"> <label for="cv" >Upload your CV</label><br> <input type="file" name="cv" placeholder="CV" id="role" required /><br> </div> <div class="element"> <input type="submit" class="btn btn-success col-md-5" value="Update"> </div> </form> and views.py def canDetails(request): if request.method=='POST': empemail=request.session print(empemail) loc=request.POST['location'] rol=request.POST['role'] print(request.FILES) cv=request.FILES['cv'] canDetails(location=loc,role=rol,cv=cv).save() messages.success(request,"Details updated successfully...!") return render(request,'canDetails.html') return render(request,'canDetails.html') is it the right way I am trying to upload.? I am saving my uploaded file to the media folder here... and here while I am doing it I am getting this error as well canDetails() got an unexpected keyword argument 'location' any suggestion will be greatly appreciated..) -
ModuleNotFoundError: No module named 'myapp.url'
i was creating my django first app. I added this code (urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.url')) ] ) from my project Urls.py file to get my html code from my app url.py, but i keep getting this error when i want to run my server. ModuleNotFoundError: No module named 'myapp.url' -
What exactly the reverse query name in its related model in Django?
I got pretty much the same problem as in Django - reverse query name clash. for the following code: class Supplier(models.Model): unique_id = models.IntegerField(unique=True) name = models.CharField(max_length=255, unique=True) rating = models.FloatField(null=True) last_updated = models.DateTimeField(auto_now=True) default_tariff = models.ForeignKey('Tariff') class Tariff(models.Model): name = models.CharField(max_length=255) supplier = models.ForeignKey(Supplier) end_date = models.DateField(null=True, blank=True) payment_method = models.ManyToManyField(PaymentMethod) region = models.ManyToManyField(Region) My question is: why does the reverse query name for Supplier.default_tariff clashes with the field name Tariff.supplier. I read the docs and I think it should be something like Supplier.default_tariff_set? -
How to get the OAuth code from the redirect URI displayed in the browser using Django URLs
I am integrating Django app with the Docusign API, for the authorization I am using OAuth2 grant_type="code", after passing all the required params to the /oauth/auth (https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature&client_id=33f*******NNNNMNMc-b478-7593294fb3ba&redirect_uri=http://localhost:3000/sales/oauth/callback) endpoint I am getting the Oauth code in the browser to the redirect URI(http://localhost:3000/sales/oauth/callback), I want to fetch this code from my django class view where I have created a path to my view as urlpatterns = [ path( "sales/oauth/callback", OAuthCallbackView.as_view(), name="OAuthCallbackView", ), ] and my view class OAuthCallbackView(APIView): def get(self, request): access_code = request.GET["code"] I want to get the auth code here, since the redirect URI path contains the code (/sales/oauth/callback?code=12312232) I am not able to hit the URL path mentioned above Is there a way I can get the Oauth code in Django -
IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name
I am creating a simple django models of doctors and department. there is not link between them and when I try to update the department then it is show me this error IntegrityError at /update_dept/1/ NOT NULL constraint failed: main_department.dept_name this error is new for me. I check other similar question also but didn't get much. so pls help me. here is my view.py file from django.shortcuts import render from .forms import Doctorslist,Departmentform from .models import Department, Doctor from django.shortcuts import redirect from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) from django.contrib.messages import constants as messages import os # Create your views here. def add_show(request): form = Doctorslist() if request.method == "POST": form = Doctorslist(request.POST, request.FILES) form.save() return redirect('/') else: form = Doctorslist() stud = Doctor.objects.all context = {'form':form, 'stu':stud } return render(request, 'main/index.html', context) def update_data(request, id): prod = Doctor.objects.get(id=id) if request.method == "POST": prod.doc_image = request.FILES['doc_image'] prod.kycdocument = request.FILES['kycdocument'] prod.name = request.POST.get('name') prod.phone_number = request.POST.get('phone_number') prod.email = request.POST.get('email') prod.city = request.POST.get('city') prod.speciality = request.POST.get('email') prod.save() messages.success(request, "Product Updated Successfully") return redirect('/') context = {'prod':prod} return render(request, 'main/update_doc.html', context) def delete_data(request,id): if request.method =='POST': pi = Doctor.objects.get(pk = id) pi.delete() return redirect('/') def add_show_dept(request): form = Departmentform() if … -
RabbitMQ mkdir: /var/db/rabbitmq/mnesia: Permission denied
I have uploaded my Django project to the server. Everything works except using Celery. The server uses FreeBSD. Erlang is uploaded, but I have a problem with RabbitMQ. I downloaded rabbitmq-server-generic-unix-3.9.7.tar.xz and then unpacked it in cd /usr/home/my_login/RabbitMQ/. When I try to start the server with cd /usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/sbin/rabbitmq-server I am getting a message about the lack of access to create a DB in the path as below mkdir: /var/db/rabbitmq/mnesia: Permission denied Failed to create directory: /var/db/rabbitmq/mnesia So I tried somehow to manually set this path to be different in cd /usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/etc/rabbitmq/rabbitmq.conf. In the file I added: RABBITMQ_MNESIA_DIR=/usr/home/my_login/RabbitMQ/rabbitmq_server-3.9.7/db/ But that didn't help either, and I still don't know how to deal with it. I can't access root or sudo commands there -
how to upload django files as background? Or how to increased file upload?
I need to increased file upload speed in Django. Any ways to do this? I guess about to upload files as a background, when user send POST request i just redirect them to some page and start uploading files. Any ways to do this? Or do you know any ways to increased upload speed? Thank you in advance -
Django: How to test a view with login_required?
I have a view on my Django app with the tag @login_required: @login_required @require_http_methods(['GET', 'POST']) def edit_result(request: WSGIRequest, result_id: str): try: result_type, result_number = EditResultService.split_result_id(result_id.lower()) except Error as e: messages.error(request, str(e)) return render(request, PAGE404_TEMPLATE) if request.POST: EditResultService.post_request(request, result_type, result_number) context = EditResultService.get_request(result_type, result_number) if context: return render(request, 'edit_result.html', context) else: return render(request, PAGE404_TEMPLATE) I am trying to write some tests to cover 100% of this view, but no matter what I do, there is no way to obtain the actual response (not the redirection). Here is the code of my test: class TestViews(TestCase): def set_up(self): self.client = Client() self.user = User.objects.create_user('aaa', 'aaa@aaa.com', 'aaa') ..... def test_edit_result_get_ok(self): self.client.login(username='aaa', password='aaa') response = self.client.get(reverse('edit_result', kwargs={'result_id': 'i1'})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, EDIT_RESULT_TEMPLATE) self.assertTrue('form' in response.context) messages = list(get_messages(response.wsgi_request)) self.assertTrue(len(messages) == 0) Is there a way to get my view covered and check the template used, messages...? -
select filter every time I add in the db it removes it from the select
Hi I would like to know how I can make a dynamic select. Let me explain, I have a select with option fields taken from the db (for example groups). I have a function that makes me choose one of these fields and adds it to me in the db (tab table containing several groups). how can I cycle the select so that when a data from the groups table is inserted in the exercises table he no longer shows it to me in the select so in a nutshell I can't have two groups in the same tab. can someone help me? -
How to pass table value into another model instances in django?
I want pass database value into another model using instance method. and then save it into db. But when i clicked submit the value doesn't save into db. this is my model.py code import datetime from django.db import models from django.contrib.auth.models import User class Customer(models.Model): id_number = models.CharField(max_length=15, null=False) name = models.CharField(max_length=100, null=False) customer_order = models.CharField(max_length=100, null=False) order_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True, auto_created=False) phone_number = models.CharField(max_length=20, null=True) def __str__(self): return self.name class SpecialOffer(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) order_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True, auto_created=False) phone_number = models.CharField(max_length=20, null=True) customer_prizes = models.CharField(max_length=100, null=True) def __str__(self): return self.customer there are two models here, for form.py here the codes : from django import forms from .models import * class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['id_number', 'name', 'customer_order', 'order_date', 'phone_number'] widgets = { 'id_number':forms.TextInput(attrs={'class':'form-control', 'type':'text'}), 'name': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}), 'customer_order': forms.TextInput(attrs={'class':'form-control', 'type':'text'}), 'order_date': forms.DateTimeInput(attrs={'class': 'form-control datetime-local', 'type': 'text', 'data-target': '#datetimepicker', 'id':'datetimepicker'}), 'phone_number' : forms.TextInput(attrs={'class':'form-control', 'type':'text'}), } class SpecialOfferForm(forms.ModelForm): class Meta: model = SpecialOffer fields = ['order_date', 'phone_number', 'customer_prizes'] widgets = { 'order_date':forms.DateTimeInput(attrs={'class':'form-control', 'type':'text'}), 'phone_number': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}, 'customer_prizes': forms.TextInput(attrs={'class':'form-control', 'type':'text'}), } ok after get the form and model, i create input form for Customer in my views.py … -
How to Make Upload filed in Django
I am making a social media website using django I but I am not able to create a profile picture section. I want to ask that how I will Able to Make a filed Where a User can Select And upload their own profile picture. Please Help me -
How to run prometheus on docker-compose and scrape django server running locally?
I am trying to setup prometheus to monitor my Django application using django-prometheus and Docker compose. I've been following some guides online but different from all the guides I've seen, I want to run Django locally for now so simply python manage.py runserver and run prometheus with docker-compose (and later add grafana). I want to do this to test it locally and later I will deploy it to Kubernetes but this is for another episode. My issue is to make the local running django server communicate in the same network as the prometheus running container because I get this error in the /targets on prometheus dashboard: Get "http://127.0.0.1:5000/metrics": dial tcp 127.0.0.1:5000: connect: connection refused These are my docker-compose file and prometheus configuration: docker-compose.yml version: '3.6' services: prometheus: image: prom/prometheus volumes: - ./prometheus/:/etc/prometheus/ command: - '--config.file=/etc/prometheus/prometheus.yml' ports: - 9090:9090 prometheus.yaml global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: prometheus static_configs: - targets: - localhost:9090 - job_name: django-app static_configs: - targets: - localhost:8000 - 127.0.0.1:8000 -
django.db.utils.DataError: length for type varchar cannot exceed 10485760
I was trying to push my code to the heroku and when I migrate my manage.py, it causes this error: django.db.utils.DataError: length for type varchar cannot exceed 10485760 . First, my length has been set to 100000000 and I change it back to 1000 and make migrations. But even after that I still got this Error. I try to search my whole files and everything is set to 1000. Help me to solve the problem! -
Create django query satisfying two conditions involving related models
I have two models, let's say: class Order(models.Model): # ... fields class Product(models.Model): quantity = models.PositiveIntegerField(null=False, blank=False, default=1) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') I want to make a query that includes all the Orders which have more than one Product related to it, or if at least one Product has a quantity greater than 1. For the first part I have this: queryset = Order.objects.annotate(products_count=Count('products')).filter(products_count__gt=1) I am stuck on adding the OR condition to also include the other condition. Thank you so much in advance. -
Dockerize a React-Django project where the frontend is served from Django
I am serving a react app from within Django, and I trying to deploy it using docker-compose up -d --build. My project directory is as follows: root ├──project (django) | ├──frontend/ # react project is here | ├──project/ | ├──static/ | ├──Dockerfile //Dockerfile for backend image | ├──entrypoint.sh | ├──manage.py | ├──requirements.txt └──docker-compose.yaml Here is my current deploy script: # pull the official base image FROM python:3.8.12-bullseye # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update COPY /requirements.txt /usr/src/app RUN pip install -r requirements.txt # set work directory WORKDIR ~/usr/src/app COPY package.json ./ COPY package-lock.json ./ RUN npm install --silent RUN npm install react-scripts@3.4.1 -g --silent RUN npm run dev # set work directory WORKDIR /usr/src/app # copy project COPY . /usr/src/app/ # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] The error I get > => ERROR [12/18] COPY package.json ./ > 0.0s => ERROR [13/18] COPY package-lock.json ./ 0.0s ------ > > [12/18] COPY package.json ./: > ------ > ------ > > [13/18] COPY package-lock.json ./: > ------ failed to compute cache key: "/package-lock.json" not found: not found lipsumlipsumlipsumlipsumlipsumlipsumlipsumlipsum -
How to edit django default headers
I have the endpoint that return string as response within Response object from rest_framework. Response(response, status=200, headers={'age': 20}, content_type="text/plain; version=0.0.4") Above you can see my response object, as you can see only header I set up is 'age'. However when I check response.items() I can see that more headers are being added: dict_values([('Content-Type', 'text/plain; version=0.0.4'), ('age', '20'), ('Vary', 'Accept, Cookie'), ('Allow', 'GET, OPTIONS'), ('X-Frame-Options', 'DENY'), ('Content-Length', '213'), ('X-Content-Type-Options', 'nosniff')]) Is it possible to somehow delete/edit some of those headers that are being added automatically by django/rest_framework? Thanks! -
Why 404 error occurs even though I have set STATIC_ROOT and urls.py
I don't know why, but I get 404 errors when trying to use static file like this: {% static 'js/some.js' %}. Here's my urls.py urlpatterns = [ path('admin/', admin.site.urls), path("account/", include("account.urls")), path("", include("post.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is my settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static/' # media config MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / 'media/' Thanks!! -
How To Show Foreign Key Field Name instead of ID when UPDATING records in a modal Form using AJAX, Django REST API & jQuery
I have two models class Properties(models.Model): property_name = models.CharField(max_length=100) property_type = models.CharField(choices=TYPE, max_length=50) property_location = models.CharField(max_length=100) county = models.CharField(choices=COUNTY, max_length=50) number_of_units = models.IntegerField() date_created = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.property_name class Meta: verbose_name_plural = "Properties" class RentalUnits(models.Model): unit_number = models.CharField(max_length=10) property = models.ForeignKey(Properties, on_delete=models.CASCADE) no_of_bedrooms = models.IntegerField(default=0) no_of_bathrooms = models.IntegerField(default=0) rent_per_month = models.IntegerField(default=0) status = models.CharField(max_length=20, choices=STATUS) date_created = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.unit_number class Meta: verbose_name_plural = 'Units' And their corresponding serializers class PropertiesSerializers(serializers.ModelSerializer): class Meta: model = Properties fields = '__all__' class RentalUnitsSerializers(serializers.ModelSerializer): property = serializers.SerializerMethodField() class Meta: model = RentalUnits fields = ('id', 'unit_number', 'property', 'no_of_bedrooms', 'no_of_bathrooms', 'rent_per_month', 'status',) I wanted to show their foreign key names instead of IDs in a datatable and I found a good solution here so i ended up using def to_representation(self, instance): rep = super(RentalUnitsSerializers, self).to_representation(instance) rep['property'] = instance.property.property_name return rep and it gave me this { "id": 12, "unit_number": "1A", "property": 1, "no_of_bedrooms": 3, "no_of_bathrooms": 2, "rent_per_month": 60000, "status": "Occupied" }, { "id": 12, "unit_number": "1A", "property": "New Apartments", "no_of_bedrooms": 3, "no_of_bathrooms": 2, "rent_per_month": 60000, "status": "Occupied" }, Adding units & deleting units still works fine. My problem now comes up when I want …