Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Application Error (Django web App)
Hey, I am new in development and I don't understand all of this error please help me. how can I fix this? need help! -
Getting the whole linkvertise referrer address in django
I'm using linkvertise on my site and im trying to get the referrer with django, when i get redirected from linkvertise, request.META.get('HTTP_REFERER') returns https://linkvertise.com, not the whole link like linkvertise.com/code, is there anyway i can get the whole link to check if it's mine so people can't create fake links redirecting to my site? -
Django 3.2 base template fails with error: Invalid block tag on line 11: 'raw'. Did you forget to register or load this tag?
I searched the internet and they said to use {%block raw}. This fails with the error: only one raw block allowed. I also tried substituting {% verbatim %}. This also failed. Why does Django 3.2 fail with: Invalid block tag on line 11: 'raw'. Did you forget to register or load this tag? The template is: {{"{% extends 'webapp/base.html' "}}{{ "%" }}} {{"{% block content "}}{{ "%" }}} {{"{% if products "}}{{ "%" }}} <div class="row mx-2"> {{"{% for product in products "}}{{ "%" }}} <div class="col-12 col-sm-6 col-md-4 px-2 mb-3"> <div class="card"> <img src="{{product.image}}" class="img-fluid" style="padding: 30px" alt="{% raw %}{{product.title}}{% endraw %}" /> <div class="card-body"> <h5 class="card-title">{% raw %}{{product.title}}{% endraw %}</h5> <p class="card-text"> A beautiful {% raw %}{{product.title}} for ${{product.price}}{% endraw %}. </p> <a href="/" class="btn btn-primary">Buy Now</a> </div> </div> </div> {{"{% endfor "}}{{ "%" }}} </div> {{"{% else "}}{{ "%" }}} <p>No products available.</p> {{"{% endif "}}{{ "%" }}} {{ "{% endblock " }}{{ "%" }}} -
In Django Select2 how to exclude request user from search?
This method will exclude request user from many to many fields of users list to add requested user to forms forms.py from django_select2 import forms as s2forms class CoAuthorsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = ["username__istartswith", "email__icontains"] class PostForm(forms.ModelForm): other_author = forms.ModelChoiceField( queryset=None, widget=CoAuthorsWidget( model=User, ) ) def __init__(self, user, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['other_author'].queryset = User.objects.exclude(id=user.id) class Meta: model = Post fields = 'other_author' widgets = { 'other_author': CoAuthorsWidget( attrs={ 'class': 'bg-olive-lite', 'style': 'width: 100%', } ) } views.py form = PostForm(user=request.user , data=request.POST, files=request.FILES) -
Ordering and ranking a QuerySet in Django based on existing model field data, limited to the first few rankings only?
I'm having some trouble with Window() expressions and Rank() for some multi-step rankings of QuerySets for a sports simulation I'm building. I have three core models: Team, Division and Conference. Here's a stripped down version of them to illustrate their relations to each other. class Conference(models.Model): name = models.CharField(max_length=200) class Division(models.Model): name = models.CharField(max_length=200) conference = models.ForeignKey( Conference, on_delete=models.CASCADE, related_name='divisions' ) class Team(models.Model): division = models.ForeignKey( Division, on_delete=models.CASCADE, related_name='teams', ) I'm creating rankings for each of the teams in their respective divisions and conferences based on their TeamStanding at the start of every week (wins, losses, etc.). The rankings will be saved in a TeamRanking instance (their numbered rank in their division 1-4, conference 1-16, and league-wide 1-32) which has a OneToOne relationship with TeamStanding (one of each per team, per week). Stripped down version of the above models as well: class TeamStanding(models.Model): team = models.ForeignKey( Team, on_delete=models.CASCADE, related_name='team_standings', ) # All the standing data fields class TeamRanking(models.Model): standing = models.OneToOneField( TeamStanding, related_name='ranking', on_delete=models.CASCADE, ) # All the rankings fields Here's how the division rankings are calculated currently: division_rank_qs = TeamStanding.objects.filter( team__division__exact=division ).annotate( rank=Window( expression=Rank(), order_by=[ F('wins').desc(), F('losses'), F('points_for').desc(), F('points_against') ], ) ) Then to access the ranks: for ranked_div_standing … -
django mysql dynamic table creation on a Model save
I would like to create additional tables when I call Model.save() (INSERT). But I keep getting this error: django.db.transaction.TransactionManagementError: Executing DDL statements while in a transaction on databases that can't perform a rollback is prohibited. I tried to create additional tables inside Model.save() and using a pre_save() signal, I get the same error. This is a pre_save solution attempt: from django.db.models.signals import pre_save from django.dispatch import receiver from django.db import connection @receiver(pre_save, sender=MyModel, dispatch_uid="create_tags") def create_tags(sender, instance, **kwargs): print("debug, signal pre_save works") try: # if obj exists in MyModel table, skip tag table creation existing_obj = MyModel.objects.get(name=instance.name) print("debug, obj exists") except MyModel.DoesNotExist: with connection.schema_editor() as schema_editor: schema_editor.create_model(MyModel2) Stack: Django, MySQL. What I wanted to implement is to create additional tables for the instance that is being inserted. -
DRF ManyToMany field seralize
I have the following model class Contact(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='contacts') friends = models.ManyToManyField('self', blank=True) def __str__(self): return self.user.username When the user log-in, the client make a HTTP request to the following view to get user friends. class ContactAPIView(generics.RetrieveAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer lookup_field = 'user__username' The data returned: THE QUESTION IS: How can I serializer the 'friends' field in a way that I can get the id, user.id and user.username. -
By Convention, when creating an application in django is it more common to access the backend directly or use API's to make the CRUD?
I'm a beginner and now that I've done all the views and html, I'm in a connection phase with the backend, I would like to know what is most used, to do it correctly. PS: this will have a large number of users -
Inline CSS not following @media min-width and max-width properties
I am creating a pricing page in my Django app which has 3 columns. If the screen size is more than 768 pixels, I want it to show all 3 columns side-by-side. But if it's less 768 pixels, I want there to only be 1 column with the different pricing options on top of each other. For some reason, the @media properties are not being followed. It doesn't matter what the screen size is, the page is always showing 3 columns. The below screenshot should only have 1 column (like most mobile-friendly pages) Current page: Js Fiddle - LINK The strange thing is that in this JS Fiddle, it does seem to be following the @media screen and (max-width) properties. Code: <html> <head> <style> @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800); @import url(https://fonts.googleapis.com/css?family=Montserrat:800); /* MOBILE CUSTOMIZATIONS */ @media screen and (max-width: 767px) { .snip1214 .plan { width: 90%; margin: 0 auto; background-color: blue; } } @media screen and (min-width: 768px) { .snip1214 .plan { margin: 0; width: 25%; position: relative; float: left; background-color: #ffffff; border: 1px solid rgba(0, 0, 0, 0.1); } } html { height: 100%; } body { background-color: #212121; display: flex; justify-content: center; align-items: center; flex-flow: wrap; margin: 0; height: … -
Django filter statement error- invalid literal for int() with base 10:
I have 2 tables. I wanted to filter records from the second table based on filtered value from the first table. There is something wrong in my second filter statement. If anyone can help me to sort it out? report_table_data=report_table.objects.filter(cn_number=Master_table_data.cn_number)) My codes are as below. Models.py class Master_table(models.Model): sl_no = models.AutoField(primary_key=True) cn_number = models.CharField(max_length=10, null=False) class report_table( models.Model ): cn_number = models.ForeignKey(Master_table, on_delete=models.CASCADE) remarks = models.CharField( max_length=20, null=False ) Views.py def any_view(request): Master_table_data=Master_table.objects.get(sl_no=request.GET['key']) report_table_data=report_table.objects.filter(cn_number=Master_table_data.cn_number)) This throws below error. ValueError: invalid literal for int() with base 10: 'USS2000203' -
can't refresh the data in a DIV python Django nor the page after a jquery
Let me start by saying I have 2 variables in an HTML template(messages and users) and I have multiple buttons that when one of them is clicked it calls a jquery code that sends a post request to a Django server and it returns an update to a variable(messages) however, it's not updating the loop, I also tried to return a new HTML page that contains the new variable updated but the jquery is not updating the whole page with the new HTML if I can update the variable alone it would be better and if I can't do that how can I make jquery use the new HTML page the python code i used to return the update to the varialbe messages: if request.method == 'POST': send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2) rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId')) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) print(messages) return HttpResponse(list(messages)) and the code i used to return new HTML template: m = Message.objects.filter(to_id=2).order_by('-id') users = {} for i in m: if users.get(i.from_id.username) == None: users[i.from_id.username] = User.objects.get(id=i.from_id.id) users = list(users.values()) send=Message.objects.filter(from_id=users[0].id,to_id=2) rec=Message.objects.filter(from_id=2,to_id=users[0].id) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) if request.method == 'POST': send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2) rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId')) messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True) print(messages) return render(request,'psych.html',{"users":users, "messages":list(messages)}) return render(request,'psych.html',{"users":users, "messages":list(messages)}) the HTML code and jquery code that uses the variable and … -
password reset emails are coming to the host email
I'm making an e-commerce but it sends the password confirmation email to the host. I use django builtin password reset views so I have no idea path('password-reset/', PasswordResetView.as_view( ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( ), name='password_reset_complete'), is there a way to edit the email that is sent to? -
Compare existing Django model's instances for matching fields?
I am working on a fairly difficult django query. The query needs to check against all of the Student model instances, and check if any 2 instances have 2+ matching database fields. I have this so far which works if I throw in a hard-coded search term or the value is grabbed from a form input value. Student.objects.annotate( match_count=Case(When(full_name='hardcodedvalue', then=1), default=0, output_field=IntegerField())).annotate( match_count=F('match_count') + Case(When(phone_number='hardcodedvalue', then=1), default=0, output_field=IntegerField())).annotate( match_count=F('match_count') + Case(When(student_email='hardcodedvalue', then=1), default=0, output_field=IntegerField()) ).filter(match_count__gt=1) This works great when compared to hardcoded value which is really a form input. If any 2 fields come back as a match, then it returns the correct result. Now I am struggling to run the query in a similar way, to query against items already existing in the database. I need to run a check that instead of checking against a form input, it checks all of the Student models fields. For example full name would have to check against... full_name=Student.objects.all().value('full_name') -
Azure pipeline not connecting to database service while running tests
I'm trying to run the tests of a Django application on azure with Azure pipelines. But every time I try to connect to the database I run with an error. The .yml file used for the pipeline is this: resources: containers: - container: pg12 image: postgres:12 env: POSTGRES_USER: beta POSTGRES_PASSWORD: beta POSTGRES_DB: beta ports: - 5432 # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 variables: - name: DJANGO_SETTINGS_MODULE value: config.settings.production - name: DJANGO_SECRET_KEY value: <redacted> - name: DEBUG value: False - name: DATABASE_URL value: postgres://beta:beta@localhost:5432/beta trigger: - qa pool: vmImage: ubuntu-latest strategy: matrix: Python37: PYTHON_VERSION: '3.7' maxParallel: 3 services: postgres: postgres:12 steps: - script: printenv - task: UsePythonVersion@0 inputs: versionSpec: '$(PYTHON_VERSION)' architecture: 'x64' - script: | sudo apt install -y postgresql-client # sudo psql --host=postgres --username=postgres --command="SELECT 1;" - task: PythonScript@0 displayName: 'Export project path' inputs: scriptSource: 'inline' script: | """Search all subdirectories for `manage.py`.""" from glob import iglob from os import path # Python >= 3.5 manage_py = next(iglob(path.join('**', 'manage.py'), recursive=True), None) if not manage_py: raise SystemExit('Could not find a Django project') project_location = path.dirname(path.abspath(manage_py)) print('Found Django project in', project_location) print('##vso[task.setvariable variable=projectRoot]{}'.format(project_location)) - script: | python -m … -
Django FileNotFoundError: [Errno 2] No such file or directory: 'train_mean.joblib' after deployed in Ubuntu, but working in localhost
im deploying dajngi to ubuntu (apache), running fine on my local, but error when deployed on Ubuntu server. the error: [Fri Oct 01 16:59:25.938641 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] File "/home/ubuntu/prediction/predict/views.py", line 26, in __init__ [Fri Oct 01 16:59:25.938646 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] self.values_fill_missing = joblib.load("train_mean.joblib") [Fri Oct 01 16:59:25.938650 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] File "/home/ubuntu/prediction/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 577, in load [Fri Oct 01 16:59:25.938654 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] with open(filename, 'rb') as f: [Fri Oct 01 16:59:25.938658 2021] [wsgi:error] [pid 58417:tid 140031275181824] [remote 140.213.196.122:39872] FileNotFoundError: [Errno 2] No such file or directory: 'train_mean.joblib' views.py : from django.shortcuts import render from django.http import JsonResponse import joblib import pandas as pd import numpy as np import os class LogisticRegression: def __init__(self): path_to_artifacts = '' self.values_fill_missing = joblib.load(path_to_artifacts + 'train_mean.joblib') self.scaler = joblib.load(path_to_artifacts + 'min_max_scaler.joblib') self.model = joblib.load(path_to_artifacts + 'log_reg.joblib') The dir structure: -
How to avoid double saving after defining the `Save` method on the Model?
I have defined a Save method in my model for the order fields. Now, when I do some manipulations with the Order field in View and call save() - I save twice - in View save() and Model save(). Because of this, the problem! How to solve this problem? How to make Save work only when creating a model object? And don't work save when I save() in Views -
request.POST data field doesn't get to cleaned_data of form
In views.py I've got a method called signup: def signup(request): context = {} if request.method == 'POST': form = SignUpForm(request.POST) print("request", request.POST) if form.is_valid(): user = form.save(commit=False) login(request, user) return redirect('index') else: context['form'] = form else: # GET request form = SignUpForm() context['form'] = form return render(request, 'registration/signup.html', context) Request print gives me all the fields a user entered: request <QueryDict: {'csrfmiddlewaretoken': ['***'], 'username': ['12312312gdsgdsg'], 'email': ['123123fsdfesgf@gmail.com'], 'password1': ['123fhfhfh'], 'password2': ['989898gdfjgndf']}> When I call form.is_valid() it gets to clean data of my form of forms.py: class SignUpForm(UserCreationForm): username = forms.CharField( label="username", max_length=30, required=True, widget=forms.TextInput( attrs={ 'type': 'text', 'placeholder': 'Username', } ), ) email = forms.EmailField( label="email", max_length=60, required=True, widget=forms.TextInput( attrs={ 'type': 'text', 'placeholder': 'Email', } ), ) password1 = forms.CharField( label="password1", required=True, widget=forms.PasswordInput( attrs={ 'type': 'password', 'placeholder': 'Password', } ), ) password2 = forms.CharField( label="password2", required=True, widget=forms.PasswordInput( attrs={ 'type': 'password', 'placeholder': 'Confirm Password', } ), ) def clean(self): cleaned_data = super(SignUpForm, self).clean() print("cleaned data", cleaned_data) password = cleaned_data["password1"] confirm_password = cleaned_data["password2"] if password != confirm_password: self.add_error('confirm_password', "Password and confirm password do not match") return cleaned_data class Meta: model = ServiceUser fields = ('username', 'email', 'password1', 'password2') The form's cleaned data print returns me the same dictionary as the post, but … -
how to restore database 'postgres' from postgresql
I am using local postgresql and pgadmin 4. I dropped database 'postgres' and now pgadmin won't open. How can I restore 'postgres' or fix this issue? -
Django Rest Framework ordering isnt working
Everything is imported, it might not be working because of get_queryset function, but i am not sure. class ShowStats(ListAPIView): serializer_class = StatsSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) ordering_fields = ('date', 'views', 'clicks', 'cost', 'cpc', 'cpm') ordering = ('views',) def get_queryset(self): return Stats.objects.filter(date__range=[self.kwargs['from'], self.kwargs['to']]) def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response_list = serializer.data for i in range(len(response_list)): response_list[i]['cpc'] = response_list[i]['cost'] / response_list[i]['clicks'] response_list[i]['cpm'] = response_list[i]['cost'] / response_list[i]['views'] * 1000 return Response(data=response_list) -
Deploy Reactjs inside Django app to heroku
As in the title, I currently have a django project, and have reactjs inside as an app, i follow the tutorial from Tech With Tim https://youtu.be/JD-age0BPVo but he didnt do the deployment step, Most deployment guides show seperate frontend and backend folder, I only found this guide which describe my exact situation (using react,webpack inside django) in option 1 but it isnt so detail https://mattsegal.dev/django-spa-infrastructure.html Can someone help me with deployment, im just a beginner and this is my first project in django, im pretty confused -
Django Add new column and assign values based on another table column values
I have a 3 models: class Status(DjangoEnum): Status1 = "Status1" Status2 = "Status2" Status3 = "Status3" class ABC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) variable_1 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class DEF(models.Model): abc = models.ForeignKey(ABC, on_delete=models.CASCADE) variable_2 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class GHI(models.Model): def = models.ForeignKey(DEF, on_delete=models.CASCADE) variable_3 = models.CharField( choices=Status.choices(), default=Status.Status1, max_length=50, ) I want to add a new column "Current_Status"(similar to variable_3 in GHI) in the class ABC. The values that need to be filled in this new column "Current_Status" are based on the values of variable_3 in class GHI. For example, let's assume that Current_Status(in ABC) contains the most frequent value of variable_3(in GHI) among all the records(corresponding to all the DEF records associated with the current ABC record). How can I add this column so that the existing records in the table ABC are filled with values based on variable_3 in class GHI? -
django This backend doesn't support absolute paths
I am getting this error after integration aws S3 bucket. My images are uploading on aws but why I am getting this error?. here is my code for uploading image: if self.profile_pic: img = Image.open(self.profile_pic.path) out_put_size = (200,200) img.thumbnail(out_put_size) img.save(self.profile_pic.path,quality=80,optimize=True) I found few question on stack overflow on this topic where said I need to be use name instead of path but I am not understanding how to use name instead of path? -
Django model formset - data for first nested child form missing in post method
I am using Django 3.2 and crispy-forms 1.11.2 I have a model and form defined like this: /path/to/myapp/models.py class Foo(models.Model): pass class FooChild(models.Model): parent = models.ForeignKey(Foo, on_delete=models.CASCADE) title = models.CharField(max_length=16) /path/to/myapp/forms.py class FooChildForm(ModelForm): class Meta: model = FooChild fields = "__all__" class FooChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( 'title', ) self.render_required_fields = True /path/to/myapp/views.py class FooCreateView(CreateView): model = Foo def __init__(self, **kwargs): super().__init__(**kwargs) self.choice_formset = inlineformset_factory(Foo, Child, form=FooChild, extra=9) def get(self, request, *args, **kwargs): form = self.form_class() p = self.model() formset = self.choice_formset(instance=p) helper = ChildFormSetHelper() helper.template = 'bootstrap/table_inline_formset.html' helper.form_tag = False return render(request, 'myapp/create.html', {'form' : form, 'formset': formset, 'helper': helper}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if form.is_valid(): new_foo = form.save(commit=False) new_foo.creator = request.user new_foo.save() formset = self.choice_formset(request.POST or None, instance=new_foo) formset.save() # <- formset loses first element # request.POST.get('choices-0-title') # 'Choice Two' <- (expected 'Choice One') # request.POST.get('choices-1-title') # 'Choice Three' # request.POST.get('choices-2-title') # 'Choice Four' # request.POST.get('choices-3-title') # 'Choice Five' /path/to/myapp/templates/myapp/create.html {% block content %} <div class="container-lg"> <form id="frm-foo-create" method="post"> {% csrf_token %} <div class="row" style="margin: 30px 0px;"> <div class="col-lg-12"> <h2>Create a New Foo</h2> <br /> {% crispy form %} {{ form|as_crispy_errors }} {% crispy … -
why my dropdown menu not working on some page
I tried to learn django a few day ago and make a simple website use that, but for a reason my dropdown in home page didn't work but in another page it's work properly. Here my html template for that <div class="dropdown-menu"> {% for category in links %} <a class="dropdown-item" href="{{ category.get_url }}">{{category.category_name}}</a> {% endfor %} </div> and here my code for django urls.py urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='product_by_category'), ] and here my code for links references def menu_links(request): links = Category.objects.all() return dict(links = links) i don't know why in my home page the dropdown button didn't work but in another page it work. i tried to find on my navbar templates and i think there is no problem there but the dropdown still not working and i tried to find on settings.py(to check installation app) but i did it anyone have idea where the problem is? -
How to hide nested object's name in Django Rest Framework serializer?
I have two models: Company and ContactCompany Company model is a base model and ContactCompany has some specific fields. They are connected via a foreign key. There are two serializers CompanySerializer and ContactCompanySerializer. Models: class Company(CoreModel): name = models.CharField( max_length=128, verbose_name=_("Company Name"), unique=True, ) address = models.TextField(null=True, blank=True, verbose_name=_("Address")) sector = models.ForeignKey( "contact.Sector", on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_("Sector"), related_name="companies", ) city = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_("City"), related_name="companies", ) class ContactCompany(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="contact_companies", null=True, blank=True, ) note = models.TextField(null=True, blank=True, verbose_name=_("Note")) website = models.CharField( null=True, blank=True, max_length=128, verbose_name=_("Website") ) Serializers: class ContactCompanySerializer(serializers.ModelSerializer): company = CompanySerializer() integration_requirements = serializers.ListSerializer( child=serializers.CharField(), required=False, ) statuses = StatusSerializer(many=True, read_only=True) current_status = StatusSerializer(required=False) contact_people = ContactPersonSerializer(many=True, read_only=True) responsible_company = serializers.CharField( source="responsible_company.name", read_only=True ) class Meta: model = ContactCompany fields = ( "id", "company", "website", "responsible_company", "note", "integration_requirements", "current_status", "statuses", "contact_people", ) class CompanySerializer(serializers.Serializer): name = serializers.CharField() is_active = serializers.BooleanField(required=False) city = serializers.CharField(source="city.name", required=False, allow_null=True) country = serializers.CharField( source="city.country.name", required=False, allow_null=True ) sector = serializers.CharField( source="sector.name", required=False, allow_null=True ) Example json response: { "id": 1, "company": { "name": "Company name", "is_active": true, "city": "City", "country": "Country", "sector": "Clothing" }, "website": "test", "note": "Note" } In the json response I want to delete …