Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unhashable type 'list' when i enter on change_list in Django
I search for days for a solution for this problem. after touching the admin.py file to override the get_queryset and get_form methods I ran into the unhashable type 'list' error, which has no information on where the error is located. I removed the override for the get_queryset and get_form methods, but I still get the same result. [The error][1] I find this error when I want to filter a list by overriding the get_queryset method or when I try to enter an element of the form's list. The files in my project are as follows: APP => Main admin.py @admin.register(Notification) class NotificationsAdmin(admin.ModelAdmin, ExportCsvMixin): form = NotificationForm add_form = NotificationForm list_display = ('title', 'description', 'created_at', 'updated_at', 'author') fieldsets = ( ('Information', { 'fields': ('author', 'title', 'subject', 'description', 'signature') }), ('Images', { 'fields': ('banner', 'image', 'image2', 'image3') }), ('Send to', { 'fields': ( 'send_to', 'send_all', ) }), ('Logs', { 'fields': ('created_at', 'updated_at') }), ) readonly_fields = ('created_at', 'updated_at') actions = ['export_as_csv'] list_per_page = 20 # list_max_show_all = 30 def get_form(self, request, obj=None, **kwargs): if request.user.groups.filter(name="RSM's").exists(): self.readonly_fields = ('author', 'created_at', 'updated_at') else: self.readonly_fields = ( 'created_at', 'updated_at', ) form = super(NotificationsAdmin, self).get_form(request, **kwargs) form.current_user = request.user return form # get_queryset will return the … -
Admin Page and Home Page broken after set up environ in Django
I created an application with Django backend and React frontend. In the project, I place an .env file in the root folder my_project/ .env my_app/ __init__.py apps.py settings.py urls.py views.py wsgi.py frontend/ public/ src/ build/ static/ js/ main.4dfd1f01.js css/ main.5c1407a3.css Then I use "django-environ" as my env library and do the setting as following in setting.py import os import environ ENV = environ.Env( DEBUG=(bool, False) ) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Take environment variables from .env file environ.Env.read_env(os.path.join(BASE_DIR, '.env')) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'frontend/build'], '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', ], }, }, ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'frontend/build/static' ] urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('sub-app/', include('sub-app.urls')), path('', TemplateView.as_view(template_name='index.html')), ] Everything works fine except my root URL (localhost:8000/) and admin URL (localhost:8000/admin): The problem on admin: when I input localhost:8000/admin in the browser, it simply redirects to a nonsense URL (like: http://127.0.0.1:8000/127.0.0.1:8000/sub-app/ca/admin/) **I don't even have any 'ca' anywhere in any of my urls.py … -
How to update GeoDjango model with area fields
Here the model: from django.contrib.gis.db import models class City(models.Model): mpoly = models.MultiPolygonField() area = models.IntegerField(null=True) I want to update all records at once to set the area. I've tried : from django.contrib.gis.db.models.functions import Area, Transform City.objects.all().update(area=Area(Transform("mpoly", 2154))) Which fails with "DataError: value too long for type character varying(8)"... Do you have an elegant one liner to do it ? -
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
def trash_view(request): global i, addr, passwrd, conn if request.method == 'POST': imap_url = 'imap.gmail.com' conn = imaplib.IMAP4_SSL(imap_url) conn.login(addr, passwrd) conn.select('"[Gmail]/Trash"') result1, data1 = conn.search(None, "ALL") mail_list = data1[0].split() text = "You have reached your trash folder. You have " + str(len(mail_list)) + " mails in your trash folder. To search a specific email say search. To go back to the menu page say back. To logout say logout." Hi friends, while i can work on "INBOX" , for "TRASH" section, it gives me this error"imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED". how can i solve this? Thank you -
Forward slash "/" vs "os.path.join()" vs "joinpath()" for STATIC_ROOT and MEDIA_ROOT (Django)
I found there are 3 concatenation ways using forward slash "/", "os.path.join()" or "joinpath()" for "STATIC_ROOT" and "MEDIA_ROOT" as shown below and these 3 concatenation ways work properly for me. Forward slash "/": # "settings.py" STATIC_ROOT = BASE_DIR / 'static' MEDIA_ROOT = BASE_DIR / 'media' "os.path.join()": # "settings.py" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') "joinpath()": # "settings.py" STATIC_ROOT = BASE_DIR.joinpath('static') MEDIA_ROOT = BASE_DIR.joinpath('media') So now, which way do you recommend to use, forward slash "/", "os.path.join()" or "joinpath()" for "STATIC_ROOT" and "MEDIA_ROOT"? -
Heroku. ImportError: cannot import name 'ugettext_lazy' [duplicate]
I have deployed my project to Heroku. But I got "Internal server error" "ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/init.py)" Yes, I know that I should write "gettext_lazy" instead. But I can't find this file in my project. I got this error only after deploy. I don't understand where it is situated. Help me, please. -
Forward slash "/" concatenation for STATIC_ROOT and MEDIA_ROOT (Django)
I found sometimes forward slash "/" is used to concatenate "BASE_DIR" and "static" or "media" for "STATIC_ROOT" and "MEDIA_ROOT" in "settings.py" as shown below: # "settings.py" # Here STATIC_ROOT = BASE_DIR / 'static' # Here MEDIA_ROOT = BASE_DIR / 'media' So, it's possible to concatenate BASE_DIR which is 'PosixPath' type and 'static' which is 'str' type with forward slash "/". But when I tried to concatenate 'str' type and 'str' type with "/": # "settings.py" STATIC_ROOT = 'abc' / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'str' and 'str' And for 'int' type and 'str' type with "/": STATIC_ROOT = 123 / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'int' and 'str' Then for 'MyClass' type and 'str' type with "/": # "settings.py" class MyClass: pass STATIC_ROOT = MyClass() / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'MyClass' and 'str' So, can we only concatenate 'PosixPath' type and 'str' type with forward slash "/"? Aren't there any other types to concatenate with forward slash "/"? -
Django admin won't load on my local after logging in
I'm new to python and django. I've copied my production app, that another developer wrote, onto my local. It's working perfectly. When I run django admin I get the login form. But when I enter my ID and PW I get redirected to the same login form, only it's blank; I never get logged in. The server console reads: [26/Apr/2022 06:25:21] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 [26/Apr/2022 06:25:21] "GET /admin/ HTTP/1.1" 302 0 [26/Apr/2022 06:25:21] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 11020 I don't understand what's needed to change or get added. Any help appreciated. -
How do i pass list to ModelMultipleChoiceField
This is the participant selection form class EventFormAdmin(ModelForm): name = forms.TextInput(attrs={'class':'form-control'}), manager = forms.Select(attrs={'class':'form-select'}), venue = forms.Select(attrs={'class':'form-select'}), event_date = forms.TextInput(attrs={'class':'form-control'}), participants = forms.ModelMultipleChoiceField( **queryset=Participant.objects.filter().values(participant_list),** #filter for participants who applied for a specific event widget=forms.CheckboxSelectMultiple ), description = forms.Textarea(attrs={'class':'form-control'}), class Meta: model = Event fields = ('name', 'manager', 'venue', 'event_date', 'participants', 'description') How do i put participant_list in ModelMultipleChoiceField in the function, I described the filter by values that I try to pass to the form field def update_event(request, event_id): event = Event.objects.get(pk=event_id) participant_list = Participant.objects.filter( event = event_id ) if request.user.is_superuser: form = EventFormAdmin(request.POST or None, instance=event) else: form = EventForm(request.POST or None, instance=event) if form.is_valid(): form.save() return redirect('all_events') return render(request, 'events/update_event.html', { 'participant_list':participant_list, 'event': event, 'form':form }) Thanks -
How to display multiple views in a Django project's template?
I have a Django project with multiple apps and I would like to manage the template from the project root folder. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', "DIRS": [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': {...} }] In the homepage index.html of the project I'm trying to display num_exchanges and num_accounts generated in the views.py of app1 and app2. The problem is that only num_exchanges is printed not the second variable. If I switch the include in urlpatterns then the second variable is generated not the first one. How can I print both variables ? urls.py (project) urlpatterns = [ path('admin/', admin.site.urls), url(r"^", include("app1.urls"), name='app1'), url(r"^", include("app2.urls"), name='app2'), ] index.html (project) {% load static %} {% block content %} <h2>App1</h2> <p>Records in database:</p> <ul> <li><strong>Exchanges:</strong> {{ num_exchanges }}</li> </ul> <h2>App2</h2> <p>Records in database:</p> <ul> <li><strong>Account:</strong> {{ num_accounts }}</li> </ul> {% endblock %} views.py (app1) from django.shortcuts import render from app1.models import Exchange def app1_stats(request): num_exchanges = Exchange.objects.count() context = { 'num_exchanges': num_exchanges } return render(request, 'index.html', context=context) urls.py (app1) from django.urls import path from app1.views import app1_stats urlpatterns = [ path('', app1_stats, name='index'), ] views.py (app2) from django.shortcuts import render from app2.models import Account def app2_stats(request): num_accounts = Account.objects.count() context = { … -
own authenticate backend django
i want to do an authenticate backend to authenticate users that i've in a web services but i don't have a class user, so how can i do this backend to authenticate the users that i try to login ? i have this function to consumed the web services: def web_service (): user = request.POST['username'] passwd = request.POST['password'] result = cliente.service.execute('{\ "user":"portalServicios",\ "password":"pechuga",\ "object":"user",\ "command":"authenticate",\ "login":"'+ user +'",\ "pass":"'+ passwd +'"\ }') result_dict = json.loads(result) -
How to get POST and create message using DetailView on Django
I have Post model and Message model. I want to create message on one post and preview it message. I can't think of how I can do this using DetailView Class. How can I do this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message( user = request.user, post = self.post, body = request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
Create a model object when creating a user in Django, UNIQUE constraint failed
I have this model: class Family(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=False) def __str__(self): return self.name class Meta: ordering = ['name'] And I am also using this function to create a family object when a user is created: @receiver(models.signals.post_save, sender=User) def user_created(sender, instance, created, **kwargs): if created: Family.objects.create(user=instance) I have a couple questions: I am getting an django.db.utils.IntegrityError: UNIQUE constraint failed: family_tree_family.name error, how to resolve it? How to use the **kwargs in user_created function. I create users using curl. -
Debugging an elusive edge case where browser reloads randomly
I've spent weeks trying to figure out this bug. My app has a client where a specific page will reload after she's spent some time filling in new information in a form. I can't figure out any reason for the page to reload. There are no error messages. Nothing is being captured in Sentry. So I can't reproduce locally. How do I even start going about this... could I do some sort of context capture when listening to the page reloading event? As I'm not aware of any captured necessary information I'm not even sure what do send to sentry. I'll try and save the unsaved data to local storage. But... any ideas on how to go about this is much appreciated. -
NameError: name 'mark_safe' is not defined (Django)
I have this code below in "admin.py": # "admin.py" class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None, renderer=None): output = [] if value and getattr(value, "url", None): image_url = value.url file_name = str(value) output.append( f'<a href="{image_url}" target="_blank">' f'<img src="{image_url}" alt="{file_name}" width="150" height="150" ' f'style="object-fit: cover;"/> </a>') output.append(super(AdminFileWidget, self).render(name, value, attrs, renderer)) return mark_safe(u''.join(output)) Then, I got this error below: NameError: name 'mark_safe' is not defined So, I want to import "mark_safe" but I don't know where I can get the "mark_safe" from: from <I don't know> import mark_safe Where can I get "mark_safe" from? -
Getting ERROR:500 while adding multiple objects in modelviewset
I need to add multiple users using modelviewset but i got status code 500 i did some research but it seems not working, i did overwrite the create method with many=True, and also in serializer i did overwrite init function Here is my view.py; class StudentView(viewsets.ModelViewSet): serializer_class = StudentSerializer permission_classes = (UserAccessPermissions,) def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data, many=True) serializer.is_valid(raise_exception=True) # problem is here with perform_create i think self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def get_queryset(self): username = self.request.user user = User.objects.get(username=username) if user.is_teacher: teacher = Teacher.objects.get(username=username) students = Student.objects.filter( department_name__in=teacher.department_name.all(), college_name=user.college_name) elif user.is_collegeAdmin: students = Student.objects.filter(college_name=user.college_name) return students and serializers.py class StudentSerializer(UserSerializer): department = serializers.ReadOnlyField(source='get_department_name') batch = serializers.ReadOnlyField(source='get_batch_name') college = serializers.ReadOnlyField(source='get_college_name') def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(StudentSerializer, self).__init__(many=many, *args, **kwargs) class Meta: model = Student fields = "__all__" postman body; [{ "college_name": "3d1f82fb-c2db-41f1-9dea-8d875009355f", "enrollment_no": "8520258585852", "username": "student", "full_name": "studentbhai", "mobile_no": "+918520852001", "Date_of_Birth": "2000-10-05", "password": "Stu@1234", "email": "student@gmail.com", "department_name": "1", "batch_name": "1" }, { "college_name": "3d1f82fb-c2db-41f1-9dea-8d875009355f", "enrollment_no": "8520258585852", "username": "student2", "full_name": "studentbhai", "mobile_no": "+918520852001", "Date_of_Birth": "2000-10-05", "password": "Stu@1234", "email": "student2@gmail.com", "department_name": "1", "batch_name": "1" }] -
Using Django all-auth in a standalone app: paths that do not start with 'accounts/' are NOT FOUND 404
I am using Django 3.2, and am creating a standalone user registration and management app, that uses django-allauth to handle all of the registration functionality. My stand alone app directory structure is like this: core /core settings.py urls.py # ... /django-myown-userprofile /userprofile models.py urls.py # ... myapp.tox setup.py setup.cfg # ... core/core/urls.py from django.urls import path, include urlpatterns = [ # ... path(user, include('userprofile.urls')), path(admin, admin.site.urls) ] core/django-myown-userprofile/userprofile/urls.py from django.urls import path, include urlpatterns = [ path('accounts', include('allauth.urls')), path('accounts/profile', ProfileView.as_view(), 'user-profile'), # ... ] When I attempt to access any of the allauth endpoints (e.g.): http://localhost:8000/user/accounts/login I get the error 404 Not found. It seems that django-allauth is expecting the path to be of the form: http://localhost:8000/accounts/... How do I change this behaviour of django-allauth ? -
How to integrate python script in a django project
So I am extremely new to programming, and am stuck at this issue, I am using python with Django and Mongodb for database. I need to write a service that assigns an ID (not the one assigned by mongodb) upon each user form submission. for example entry 1's ID will be [Prefix entered by user] 2101, entry 2's ID will be [Prefix entered by user] 2102, so its basically adding in the number 2100. I have no idea how and where to integrate this logic in my code. I have tried a few solutions on the internet but nothing seems to work. my code: Model.py class Writeups(Document): blog_id = 2100 title = fields.StringField(max_length=120) date_created = fields.DateField(blank=True, null=True) date_modified = fields.DateField(blank=True, null=True) version_number = fields.DecimalField(null= True , max_digits=1000, decimal_places=2) storage_path = fields.StringField(max_length=120) STRIKE_READY_BRIEF = 'SRB' STRIKE_READY_THREAT_REPORT = 'SRTR' PREFIX_CHOICES = [ (STRIKE_READY_BRIEF, 'SRB'), (STRIKE_READY_THREAT_REPORT, 'SRTR'), ] prefix = fields.StringField( max_length=4, choices=PREFIX_CHOICES, null=False, blank=False, ) views.py: @csrf_exempt def writeups_request(request): """ Writeup Request """ if request.method == 'GET': try: data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', } writeups = WriteupsFormset(data) # print(writeup) return render(request, "writeups/writeups.html", {'writeups_forms': writeups}) except Exception as e: print(e) response = {"error": "Error occurred"} return JsonResponse(response, safe=False) if request.method == … -
Problem with QuerySet filter and data display
I need to display a list of filtered participants who previously registered using the form for the event. and i don't want to use 'if' {% for participant in participants %} {% if participant.event.id == event.id %} {{ participant.first_name }} {{ participant.last_name }}, {%endif%} {% endfor %} before displaying, I have to approve the participants' applications in the ModelMultipleChoiceField (or something else) class EventForm(ModelForm): name = forms.TextInput(attrs={'class':'form-control'}), venue = forms.Select(attrs={'class':'form-select'}), event_date = forms.TextInput(attrs={'class':'form-control'}), participants = forms.ModelMultipleChoiceField( to_field_name="participants", queryset=Participant.objects.all(),#filter for participants who applied for a specific event widget=forms.CheckboxSelectMultiple ), description = forms.Textarea(attrs={'class':'form-control'}), class Meta: model = Event fields = ('name', 'venue', 'event_date', 'participants', 'description') how do I filter the list by events from the Participant model in the form above, I'm trying to display a list of participants filtering by the event for which they registered. In the form below (ParticipantForm) participants send their applications for approval to the EventForm class ParticipantForm(forms.ModelForm): first_name = forms.CharField(widget=forms.Textarea(attrs={ 'rows': '1', })) last_name = forms.CharField(widget=forms.Textarea(attrs={ 'rows': '1', })) event = forms.ModelChoiceField(queryset=Event.objects.all(), widget=forms.HiddenInput()) class Meta: model = Participant fields = ['event', 'first_name', 'last_name'] This is my first time writing on stack over flow. Sorry for mistakes -
Django ORM query works on shell but time outs in Api View
I have large list of ids and wanted to filter objects using those ids: list_of_ids = [1, 2, 3, 4, ...] MyModel.objects.filter(id__in=list_of_ids)[:20] That query works just fine from shell, but when I try to do the same thing in API View it time outs: from rest_framework.response import Response from rest_framework.views import APIView class MyModelAPIView(APIView): def get(self, request): ids = [1, 2, 3, 4, 5, ...] print(MyModel.objects.filter(id__in=ids)[:20]) return Response({}) After I got the response with a 504 status code, I see in terminal logs what the print function did: django_1 | <QuerySet [<MyModel: 231>, <MyModel: 268>, <MyModel: 269>, <MyModel: 271>, <MyModel: 272>, <MyModel: 274>, <MyModel: 275>, <MyModel: 277>, <MyModel: 280>, <MyModel: 281>, <MyModel: 282>, <MyModel: 284>, <MyModel: 285>, <MyModel: 288>, <MyModel: 289>, <MyModel: 290>, <MyModel: 291>, <MyModel: 292>, <MyModel: 294>, <MyModel: 298>]> But I can't find out why do request time outs? I could not find similar problems there -
Django OTP login using phone number
I want to authenticate user with Phone number and login with Phone number OTP, I have MSG91 api I know we need to user Custom User model but I don't Know about clear Idea For custom User model and OTP login With Phone number anyone Have answers For My Question. ** (And also forgot password using Phone number otp)** -
How to show messages using DetailView on Django
I have Message model and Post model. I want to show all messages which posted to one post. I can't think of how to get all messages at certain post using DetailView Class. How can I do this? or should I create another ListView Class for messages? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post -
Mypy with django: Define foreign key to be overridden in child class
I have an abstract base class and 2 child classes. I want to define the create_product method on the base class, but mypy errors, rightly saying that I haven't defined product on the base class. How should I do this correctly? I imagine i should declare a sort of empty field on the Base class, but I can't find any docs on this. Error: error: Unexpected attribute "product" for model "Base" [misc] Code: class Base(Model): identifier = CharField() class Meta: abstract = True @classmethod def create_product( cls, *, identifier=identifier, product=product ): return cls.objects.create( identifier=identifier, product=product # Error here ) class ChildA(Base): product = models.OneToOneField(...) class ChildB(Base): product = models.OneToOneField(...) Note I'm using the django-stubs and django-stubs-ext libraries -
Django : Why is string condition False if select_related field not coated in STR()?
In my function, my query is : mappings = MappingField.objects.filter( fl_fiche_header_flow_id=fhf.pk).order_by('fl_fiche_inside_field_position') .select_related('fl_fiche_header_flow') Why when I print (label is models.Charfield): mapping.fl_fiche_header_flow.label I got well : appli1 And when I check the condition : if mapping.fl_fiche_header_flow.label == 'appli1': I obtain False? Why do I need to str(mapping.fl_fiche_header_flow.label) in my condition for getting true? Is it only due to select_related or is it a general principle ? -
can any one tell how can i get an appropriate output only using a foreign key in models
this is my models.py file models.py from django.db import models from django.utils import timezone class Movielist(models.Model) : Title = models.CharField(max_length=1000) Description = models.TextField(blank=True) ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True) Upvote = models.IntegerField(default=0) Downvote = models.IntegerField(default=0) def __str__(self): return self.Title class Actorlist(models.Model): Name = models.CharField(max_length=1000) DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True) def __str__(self): return self.Name class ActorInMovie(models.Model): Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True, related_name='ActorInMovie') Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True,related_name='ActorsMovie') def __str__(self): return self.Movie.Title this is my views.py file views.py @api_view(['GET']) def apiOverview(request): api_urls = { 'List':'/task-list/', 'Detail View':'/task-detail/<str:pk>/', 'Create':'/task-create/', 'Update':'/task-update/<str:pk>/', 'Delete':'/task-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def MovieName(request): MovieName = Movielist.objects.prefetch_related('ActorInMovie') serializer = MovieListSerializer(MovieName, many=True) return Response(serializer.data) this is my serializers.py file serializers.py from rest_framework import serializers from .models import * class MovieListSerializer(serializers.ModelSerializer): class Meta: model = Movielist fields = "__all__" As output i am getting this as below [ { "id": 1, "Title": "KGF Chapter 1", "Description": "This is very thrilling and suspenseful movie", "ReleaseDate": "2022-04-18T16:22:03Z", "Upvote": 5, "Downvote": 2 }, { "id": 2, "Title": "RRR", "Description": "This is a south Indian movie", "ReleaseDate": "2022-04-19T06:46:54Z", "Upvote": 2, "Downvote": 3 }, { "id": 3, "Title": "Doctor Strange", "Description": "this movie is a part of marvel cinematic universe.", "ReleaseDate": "2022-04-22T07:19:07Z", "Upvote": 12, "Downvote": 7 …