Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Fix Django "127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS" in python
Whenever I Login With Agent User. Where Agent Only Have Perms to Access Leads Page and Agent Can't See Any other pages. But When I open /lead It Raise An Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS app urls.py from django.urls import path from .views import ( LeadDetailView, leadlistview,LeadCreateView, LeadUpdateView, LeadDeleteView, AssignAgentView, CatogoryListView, CatogoryDetailView, LeadCatagoryUpdateView ) app_name = "leads" urlpatterns = [ path('', leadlistview.as_view(), name='lead-list'), path('<int:pk>/', LeadDetailView.as_view(), name='lead-detail'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('<int:pk>/delete/', LeadDeleteView.as_view(), name='lead-delete'), path('<int:pk>/assign-agent/', AssignAgentView.as_view(), name='assign-agent'), path('<int:pk>/category/', CatogoryDetailView.as_view(), name='lead-catagory-update'), path('create/', LeadCreateView.as_view(), name='lead_create'), path('categories/', CatogoryListView.as_view(), name='catagory-list'), path('categories/<int:pk>/', CatogoryDetailView.as_view(), name='catagory-detail'), ] app views.py from django.core.mail import send_mail from django.shortcuts import render, redirect from django.urls import reverse from django.views import generic from .models import Lead, Agent, Catagory from django.contrib.auth.mixins import LoginRequiredMixin from .forms import (LeadModelForm, LeadModelForm, CustomUserCreationForm, AssignAgentForm, LeadCategoryUpdateForm, ) from agents.mixxins import OrganizerAndLoginRequiredMixin # Create your views here. class LandingPageView(generic.TemplateView): template_name = "landing.html" def landing_page(request): return render(request, 'landing.html') class leadlistview(OrganizerAndLoginRequiredMixin,generic.ListView): template_name = "lead_list.html" context_object_name = "leads" def get_queryset(self): user = self.request.user # initial queryset of leads for the entire organisation if user.is_organisor: queryset = Lead.objects.filter( organisation=user.userprofile, agent__isnull=False ) else: queryset = Lead.objects.filter( organisation=user.agent.organisation, agent__isnull=False ) # filter for the agent that is logged in queryset = queryset.filter(agent__user=user) return queryset def … -
Installing ruamel.yaml.clib with docker
I have a small project in django rest framework and I want to dockerize it. In my requirements.txt file there is a package called ruamel.yaml.clib==0.2.6. While downloading all other requirements is successfull, there is a problem when it tries to download this package. #11 208.5 Collecting ruamel.yaml.clib==0.2.6 #11 208.7 Downloading ruamel.yaml.clib-0.2.6.tar.gz (180 kB) #11 217.8 ERROR: Command errored out with exit status 1: #11 217.8 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"'; file='"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-n2gr5j35 #11 217.8 cwd: /tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/ #11 217.8 Complete output (3 lines): #11 217.8 sys.argv ['/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py', 'egg_info', '--egg-base', '/tmp/pip-pip-egg-info-n2gr5j35'] #11 217.8 test compiling /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c -> test_ruamel_yaml compile error: /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c #11 217.8 Exception: command 'gcc' failed: No such file or directory #11 217.8 ---------------------------------------- #11 217.8 WARNING: Discarding https://files.pythonhosted.org/packages/8b/25/08e5ad2431a028d0723ca5540b3af6a32f58f25e83c6dda4d0fcef7288a3/ruamel.yaml.clib-0.2.6.tar.gz#sha256=4ff604ce439abb20794f05613c374759ce10e3595d1867764dd1ae675b85acbd (from https://pypi.org/simple/ruamel-yaml-clib/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. #11 217.8 ERROR: Could not find a version that satisfies the requirement ruamel.yaml.clib==0.2.6 (from versions: 0.1.0, 0.1.2, 0.2.0, 0.2.2, 0.2.3, 0.2.4, 0.2.6) #11 217.8 ERROR: No matching distribution found for ruamel.yaml.clib==0.2.6 However, there is no problem … -
What is the best practice for having html tags change their style after changing URL in Django?
Suppose I have this kind of navbar, the buttons in which turn white when you click it (adding an "active" class). But if the button redirects to a new url, the navbar renders anew, and the home icon is highlighted as it is by default. How to drag that "active" class on a button after a redirect? What is the best practice in that regard? Do I ask the wrong question? -
React is not displaying Rich-Text-Content from django
I am using django as backend and react as frontend, I am using tinymce to create description in django-admin page , But react is displaying description content with html tags Ouput: <p>Best Cough Syrup</p> I used dangerouslySetInnerHTML but page is not loading any content <div dangerouslySetInnerHTML={product.description} /> Is there any way to solve this issue -
Can not implement facebook oauth into my django app
I prepared backend to imlement facebook oauth. I set up all setiings as expected in docs SOCIAL_AUTH_FACEBOOK_KEY = os.getenv("FACEBOOK_APP_KEY") SOCIAL_AUTH_FACEBOOK_SECRET = os.getenv("FACEBOOK_APP_SECRET") SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'email' } AUTHENTICATION_BACKENDS = ( # Important for accessing admin with django_social 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) This is my link to get facebook oauth page {{baseUrl}}/api/auth/social/o/facebook/?redirect_uri={{redirect_uri}} Redirect url matches to facebook app's ap domain When i am going to facebook oauth page i get Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. if i didn't give needed information, ask me for it and i will add it. -
Should I store static files in a separated S3 when deploying with AWS Elastic Beanstalk?
I've got a Django app running on AWS Elastic Beanstalk. Beanstalk created an S3 bucket to store the source code, versions, etc. I've configured the S3 bucket to store also my static files. Every time I deploy a new version of the code, eb runs the collectstatic command correctly and creates the static files, but it overrides the permissions. So for every new deploy, I need to go, select the static folder and make the objects public manually. Question: Is it correct to store my static files in the same bucket, or should I create a separate one with a public policy? Question 2: If it's better to use the same bucket, how can I define a public policy for the static folder, but not the other folders such as the source code? -
need help for change attribute of models on view
i need to change attribute of my models on views but this my code dosent work view: class TaskRequest(APIView): permission_classes = [IsBenefactor,] def get(self ,request, task_id): obj = Task.objects.get(id=task_id) if not obj: raise Http404("not found") if obj.state==obj.TaskStatus.PENDING: data={ 'detail': 'This task is not pending.' } return Response(data , status=status.HTTP_404_NOT_FOUND) else: obj.assign_to_benefactor(self , obj.assigned_benefactor) obj.save() data={ 'detail': 'Request sent.' } return Response(data , status=status.HTTP_200_OK) my code of view get object If not available return 404 error if available and state equal to PENDING return some data otherwise change state to Waiting and assigned to benefactor user but this my code doesnt work what can i do ? and my models : class Task(models.Model): class TaskStatus(models.TextChoices): PENDING = 'P', 'Pending' WAITING = 'W', 'Waiting' ASSIGNED = 'A', 'Assigned' DONE = 'D', 'Done' title = models.CharField(max_length=60) state = models.CharField( max_length=1, default=TaskStatus.PENDING, choices=TaskStatus.choices, ) charity = models.ForeignKey(Charity, on_delete=models.CASCADE) description = models.TextField(blank=True) assigned_benefactor = models.ForeignKey( Benefactor, on_delete=models.SET_NULL, null=True, ) date = models.DateField(null=True, blank=True) age_limit_from = models.IntegerField(null=True, blank=True) age_limit_to = models.IntegerField(null=True, blank=True) gender_limit = models.CharField( max_length=2, choices=User.Gender.choices, default=User.Gender.UNSET, ) def assign_to_benefactor(self, benefactor): self.state = Task.TaskStatus.WAITING self.assigned_benefactor = benefactor self.save() -
Combining ordering and pagination in Django
I am using rest_framework.pagination.LimitOffsetPagination in combination with Django's sort filter (with filter_backends = [OrderingFilter] and ordering_fields in my view). The problem is that Django appears to be applying the sort on the pagination results, and not the other way around. Analogy with a list: If the results of the get_queryset are: ['b', 'e', 'c', 'a', 'd', 'f'] Pagination is applied first (e.g. with a limit of 3): ['b', 'e', 'c'] And then the results are sorted: ['b', 'c', 'e'] The result I would expect, however, is: ['a', 'b', 'c'] Any ideas how I can get sorting applied before pagination? Thank you very much in advance. -
django create super user command
Cmd pic Cmd 2 pic Cmd 3 pic Cmd5 pic hello , I had tried to use the createsuperuser command, it did not work, please can u help? The pics show the steps i used on windows cmd . I would have written it in text but its was not getting copied. Sorry, if u are not supposed to ask these easy qustions. -
Django Rest with Vuejs
I would like to run DjangoRest and Vuejs app on the same server. Something like this: PORT 8081 -> DjangoRest 8080 -> Vuejs app Deployment is successful and everything works except static files are not served correctly. On address http://{ip}:8081 static files are served correctly but on port 80 they are not. Isn't proxy_pass only proxying the request to port 8081 and everything should work the same way it works on port 8081? Thanks! -
CORS missing allow origins with login_required Django
here it is my problem as i said in title i have an issue with cors. I created a view with a "login_required" and since i have the error "cors missing allow origin", my get request worked fine before i set the login_required. Im using Django rest Framework i tried everything, i modified settting.py with allow_host, cors_origin_white_list, corsheader in installed app, add header options in my axios request, etc... the view class essai2(APIView): serializer_class = ComSerializer def get(self, request): Pictos = Pictograms.objects.all() data = ComSerializer(Pictos, many=True).data if data: return Response(data, status=status.HTTP_200_OK) the axios request (im using reactjs) useEffect(() => { axios.get("http://127.0.0.1:8002/com/test").then(function (response) { console.log("coucou"); setpictos(response.data); }) }, []); setting.py CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_ORIGIN = ["http://localhost:3000",] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] im using the build-in django login system so if there is no user logged in i have a redirect to login page and everything works fine on the server side, datas display when im logged in but i cant get datas on the client side even if there is a user logged in. -
How to decrypt a value on a different service that it was originally encrypted with Fernet?
I'm playing around with a project that is python backend-based. I'll have Django for the "core" stuff and FastAPI for some crawlers. I'm encrpting some data to the DB with Django using the Fernet module and a custom Field. class EncryptedField(models.CharField): description = "Save encrypted data to DB an read as string on application level." def __init__(self, *args, **kwargs): kwargs["max_length"] = 1000 super().__init__(*args, **kwargs) @cached_property def fernet(self) -> Fernet: return Fernet(key=settings.FERNET_KEY) def get_internal_type(self) -> str: return "BinaryField" def get_db_prep_save( self, value: Any, connection: BaseDatabaseWrapper ) -> Union[memoryview, None]: value = super().get_db_prep_save(value, connection) if value is not None: encrypted_value = self.fernet.encrypt(data=force_bytes(s=value)) return connection.Database.Binary(encrypted_value) def from_db_value(self, value: bytes, *args) -> Union[str, None]: if value is not None: decrypted_value = self.fernet.decrypt(token=force_bytes(s=value)) return self.to_python(value=force_str(s=decrypted_value)) Everything work as expected, the problem is when I try to decrypt the value on FastAPI side: def decrypt(value: bytes): return Fernet(FERNET_KEY).decrypt(token=value) Some important information: I double check and settings.FERNET_KEY == FERNET_KEY, ie, I'm using the same key on both sides. Both services share the same DB and the function are receiving different values when reading for it. Django -> from_db_value -> value -> b"gAAAAABhSm94ADjyQES3JL-EiEX4pH2odwJnJe2qsuGk_K685vseoVNN6kuoF9CRdf2GxiIViOgiKVcZMk5olg7FrJL2cmMFvg==" FastAPI -> from_db_value -> value -> b"pbkdf2_sha256$260000$RzIJ5Vg3Yx8JTz4y5ZHttZ$0z9CuQiPCJrBZqc/5DvxiEcbNHZpu8hAZgmibAe7nrQ=". I actually enter inside the DB and checked … -
How I can Extend templates In djnago?
enter image description here {% extends "index.html" %} {% block content %} <h1>test for the extend</h1> {% endblock %} extend block is not working ? please any advice -
Set default number of entries in Django formset modal table
I have a modal which displays a formset with a list of items (see screenshot) The default number of items is 10, which I want to change. I can't figure out where the settings are to change this. This is my forms.py: class AddTrackerForm(forms.Form): cubecontainerdetail = forms.CharField(required=False, widget=forms.HiddenInput()) boolean = forms.BooleanField(required=False) id = forms.IntegerField( required=False, label='id') name = forms.CharField( required=False, label='Name') school_year = forms.CharField( required=False, label='School Year') year = forms.CharField( required=False, label='Tracker Year') tracker_type = forms.CharField( required=False, label='Tracker Type') This is my views.py: class TrackersListView(ListView): """ View list of trackers """ model = EstablishmentCubeContainer template_name = 'trackers/trackers_list.html' def get_formset(self): tracker_formset = formset_factory(AddTrackerForm, extra=0) tracker_list = CubeContainerDetail.objects.filter(year=current_year) initial_formset = [] for tracker in tracker_list: data = { 'id': tracker.id, 'name': tracker.name, 'school_year': tracker.school_year, 'tracker_type': tracker.cubecontainertag.name, 'year': tracker.year, } initial_formset.append(data) return tracker_formset(initial=initial_formset) This my html : <form method="POST" action="{% url tracker_create_url establishment.id %}" id="trainer_form">{% csrf_token %} <div id="listview" class="tab-pane active display"> {{ form.management_form }} <table class="cell-border table table-striped map_table display nowrap table-condensed" id="tracker-list-table" style="width:100%;"> <thead> <tr> <th>Selected</th> <th>ID</th> <th>Name</th> <th>School Year</th> <th>Type</th> <th>Tracker Year</th> </tr> </thead> <tbody> {% for query in form %} <tr> <td> <input type="checkbox" value={{ query.boolean }}</td> <td>{{ query.id }}</td> <td>{{ query.name.value }}</td> <td>{{ query.school_year.value }}</td> <td>{{ query.tracker_type.value }}</td> … -
How to hide field that is foreing key in serializer based on a statement
This is my serializer class SparkleTemplateSerializer(serializers.ModelSerializer): notifications = NotificationTemplateSerializer(source='notificationtemplate_set', many=True) rules = RuleTemplateSerializer(source='ruletemplate_set', many=True) class Meta: model = SparkleTemplate fields = ['id', 'name', 'description', 'enabled', 'run_schedule', 'notifications', 'rules'] I need to show and hide "notifications" field which is foreign key as you can see, but that need to happen if some variable is true or false. This is how I tried to do it, by adding the code below to a serializer, but I guess it doesn't work cuz of the fields property in Meta def to_representation(self, obj): show = NotificationTemplate._meta.get_field('show') rep = super(SparkleTemplateSerializer, self).to_representation(obj) if show is False: rep.pop('notifications', None) return rep I also tried excluding "notifications" and creating another serializer, but that doesn't work cuz "notifications" has to be there, so I was getting errors. Thanks -
DRF | Serialize Django Model differently depending on a type field
I am coming back in to Django / DRF after a long while.... I have been going over an idea where I have a Django model, called "TheModel", which basically is sorta of a slightly abstract db model which can be associated to numerous types. From a backend business logic standpoint I don't see the need to have multiple models/db tables representing each of these types separately. My hope is this will allowing a user to send along query params to get the types of TheModel they want with the types that are associated with them. If it comes to it, I can just rethink them all as separate models if it doesn't make sense going forward. If TheModel can have types 'A', 'B', 'C' and they may slightly differing JSON return structure needs, what would be the best approach from a high level top -> down for this? In the views would I want to use a ViewSet instead of a ModelViewSet? In which I may just have plain python objects representing the types that reflect the data structure I need which I will convert to from TheModel, which then gets serialized on response? Should I ditch using a … -
How to see all the recent changes of admin panel, who did it and when?
I want to see all the recent actions that has been done, how can i see it? -
Sharing data between plotly dash and django views
I want to store some json data that returns from a django view in dcc.store on app startup. I'm new to django-plotly-dash. Is there any resources I can refer to solve this. Djnago View looks like this def renderPage(requests): data = load_data() context = {} context = { 'page_data' : data } return render(requests, 'dashboard.html', context) ``` Following is the code snippet of the layout app.layout = html.Div( [dcc.Location(id="url"), dcc.Store(id="page-data"), html.Div(id="page-content")], ) -
Django call_command("makemigrations") strange behaviour
python manage.py makemigrations from commandline and call_command("makemigrations") from the django app results in different behaviour. Whereas the commandline is the expected behaviour, the call_command("makemigrations") removes my model from the migration and after calling migrate also from the database. When I use the command line and type python manage.py makemigrations I receive: Migrations for 'rest_service': rest_service\migrations\0009_tour.py - Create model Tour then python manage.py migrate, I receive: Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, rest_service, sessions, tenants Running migrations: Applying rest_service.0009_tour... OK So everything is okay. After the startup of my testsuite, I can see my test database created by django. This looks as expected with a table for my model tour. But after running this inside my tests call_command("makemigrations") call_command("migrate", database="default") the model (tour) was removed from the database. if I run makemigrations again I get this Migrations for 'rest_service': rest_service\migrations\0011_tour.py - Create model Tour and after migrate this Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, rest_service, sessions, tenants Running migrations: Applying rest_service.0010_delete_tour... OK Applying rest_service.0011_tour... OK If i only use call_command("migrate", database="default") without the makemigrations it works, but this is not a satisfying solution. Why does makemigrations inside the django app behave different compared … -
Django REST framework POST request with dynamic field inside a nested field using Serializer
I want to send a POST request in an API with the two different data samples as below. The POST data has different schema on options key depending on the choice key. The keys inside options key differ except few common fields. I want to validate the fields with the help of Serializer too. How can I solve this? Case 1 { "name": "name1", "options": { "choice": "choice1", "common_option1": value1, "common_option2": value2, "choice1_option1": value3, "choice1_option2": value4 } } Case 2 { "name": "name2", "options": { "choice": "choice2", "common_option1": value5, "choice2_option1": value6, "choice2_option2": value7, "choice2_option3": value8 } } -
How to render the timedelta of a Django datetime field vs. now?
I do have a Model Vote that contains a DateTimeField which returns the date in the template like so: Sept. 22, 2021, 10:02 a.m. # Model class Vote(models.Model): created_on = models.DateTimeField(auto_now_add=True) I now want to render the time delta between now and the time stored in the Model in the template: # Template <div> voted {{ vote.created_on|datetime_delta }} ago</div> Should render for example: voted 16 hours ago or voted 3 days ago As far as I know there is no built-in solution to this in Django, thus I tried to create an individual template filter: # Template filter from django import template import datetime register = template.Library() # Output Django: Sept. 22, 2021, 10:02 a.m. # Output datetime.now(): 2021-09-22 12:56:57.268152 @register.filter(name='datetime_delta') def datetime_delta(past_datetime): datetime_object = datetime.datetime.now().strftime("%bt. %d, %Y, %H:%M %p") print(datetime_object) # prints Sept. 22, 2021, 13:20 PM So I somehow tried to create two time objects in the same structure to calculate the time delta but can't make it fit 1:1. Anyways, I don't know if this might be a working approach and neither do I know if there are smarter solutions to this? -
Custom tag to set a variable in Django template. Emptying the value out of context?
In my Django Template I want to set a variable, to use in a html tag. But, when I'm out the for loop, the variable is empty :( <select > <option value=""></option> {% for a_status in status %} {% for r in all_status_ressources %} {% if a_ressource.id == r.0 and a_status.name == r.1 %} {% setvar "selected" as selected_status %} id ressource : {{ r.0 }}, name status : {{ r.1 }} -> [{{ selected_status }}]<br> {% endif %} selected_status : "{{ selected_status }}" {% endfor %} end loop ---------> selected_status : "{{ selected_status }}" <option value="{{ a_status.id }}" selected="{{ selected_status }}">{{ a_status.name }}</option> {% endfor %} </select> And, now the debug trace : selected_status : "" id ressource : 2, name status : "my personnal status" -> [selected] selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" end loop ---------> selected_status : "" So, when I'm out of the for loop, the varible is not set to be used in the html tag. Have you an … -
Django: How to "join" two querysets using Prefetch Object?
Context I am quite new to Django and I am trying to write a complex query that I think would be easily writable in raw SQL, but for which I am struggling using the ORM. Models I have several models named SignalValue, SignalCategory, SignalSubcategory, SignalType, SignalSubtype that have the same structure like the following model: class MyModel(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField() fullname = models.CharField() I also have explicit models that represent the relationships between the model SignalValue and the other models SignalCategory, SignalSubcategory, SignalType, SignalSubtype. Each of these relationships are named SignalValueCategory, SignalValueSubcategory, SignalValueType, SignalValueSubtype respectively. Below is the SignalValueCategory model as an example: class SignalValueCategory(models.Model): signal_value = models.OneToOneField(SignalValue) signal_category = models.ForeignKey(SignalCategory) Finally, I also have the two following models. ResultSignal stores all the signals related to the model Result: class Result(models.Model): pass class ResultSignal(models.Model): id = models.BigAutoField(primary_key=True) result = models.ForeignKey( Result ) signal_value = models.ForeignKey( SignalValue ) Query What I am trying to achieve is the following. For a given Result, I want to retrieve all the ResultSignals that belong to it, filter them to keep the ones of my interest, and annotate them with two fields that we will call filter_group_id and filter_group_name. The values of … -
What are the options to filter Enums values from Swagger documentation?
I'm using Django with drf-spectacular package to generate Swagger documentation. I was wondering is there any better approach to filter out some values from the Enum section inside Schema. Right now I've accomplished this using custom hook preprocess_schema_enums Enums are specified as a field in a models file hook.py def preprocess_schema_enums(result, generator, request, public): excluded = ['value1', 'value2'] enums_response = result['components']['schemas']['CustomEnum']['enum'] filtered = [res for res in enums_resoinse if res not in excluded] result['components']['schemas']['CustomEnum']['enum'] = filtered return result -
Django get queryset objects to call a function
I am trying to build APIs for a project in django, basically the code works in normal django but I am unfamiliar with Django rest Framework. Once the user uploads his image (post method), the ocr function needs to be called and the response should be the data returned by that OCR Function (extracted data from the image). The queryset is having id, name and image but I am unable to call ocr(). My code till now. api/models.py: from os import name from django.db import models from numpy import mod # Create your models here. # Create your models here. class PanCard(models.Model): name = models.CharField(max_length=255) image = models.ImageField() api/views.py: from django.db.models.query import QuerySet from django.http import request from pcard.forms import ImageUploadForm from django.conf import settings from numpy import generic from rest_framework import generics, status from rest_framework.decorators import api_view, renderer_classes from rest_framework.response import Response from .models import PanCard from .serializers import PanCardSerializer from .ocr import ocr class PanCardView(generics.ListCreateAPIView): queryset = PanCard.objects.all() serializer_class = PanCardSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() ############################################################################################## class PanCardViewDetails(generics.RetrieveUpdateDestroyAPIView): queryset = PanCard.objects.all() serializer_class …