Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement hmac sha1 verification in Django using Authlib
I'm using Django 3.0.7 and i'm trying to implement hmac sha1 by Authlib library. i'm using this code from authlib.oauth1.rfc5849.wrapper import OAuth1Request def verify_hmac_sha1(request): """Verify a HMAC-SHA1 signature.""" base_string = generate_signature_base_string(request) sig = hmac_sha1_signature( base_string, request.client_secret, request.token_secret) return hmac.compare_digest(sig, request.signature) But i've got this one error: AttributeError at /path/to/somewhere 'Request' object has no attribute 'uri' Request Method: POST Request URL: https://example.com/api/blog/ph Django Version: 3.0.7 Python Executable: /var/www/candych/path/to/somewhere Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders'] -
Internal server error 500 when pressing a button
I have been working really hard with lots of investigation trying to implement a follow system in my django project. When I finished with my code, everytime I press the "follow" button, the server returns this error Failed to load resource: the server responded with a status of 500 (Internal Server Error) What can I do to stop having this error? I think the problem is on the javascript of my code. views.py def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following = True resp = { 'following': is_following, } response = json.dumps(resp) return HttpResponse(response, content_type="application/json") def profile(request, username): profile, created = Profile.objects.get_or_create(user=request.user) user = User.objects.filter(username=username) if user: post_owner = get_object_or_404(User, username=username) user = user[0] is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower = following_obj.follower.count() following = following_obj.followed.count() else: post_owner = request.user args1 = { 'user_obj':user, 'post_owner': post_owner, 'follower': follower, 'following': following, 'connection': is_following, } return render(request, 'profile.html', args1) profile.html <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script> </head> <body> {% if connection %} <a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' β¦ -
Filtering by ManyToMany field length: values_list() returns, but the filtering result is empty
I have such a model in Django: class VariantTag(): saved_variants = models.ManyToManyField('SavedVariant') variant_tag_type = models.ForeignKey('VariantTagType', on_delete=models.CASCADE) Then, I am trying to get the VariantTag models with saved_variants field of length 2 which contain at least one of the id from the variant_ids pk list: het_tags = (VariantTag.objects.annotate(variant_len=Count('saved_variants'))) \ .filter(saved_variants__in=variant_ids, variant_len=2) logger.info(het_tags.all()) het_variant_ids = het_tags.values_list('saved_variants', flat=True) logger.info('******* het_variant_ids: {}'.format(het_variant_ids)) Logger output that I get is the following: <QuerySet []> ******* het_variant_ids: <QuerySet [150, 149]> Where 150 and 149 are correct ids that I am looking for. However, I need to get full QuerySet objects, how to get them? Why is it not working? -
Django: how to mask admin app url to separate URL
I'm looking to reconfigure the Django Admin Site so it routes directly to an app's admin as opposed to having to navigate through the existing admin panel to said app's admin. My urls are simply configured with the standard admin: urlpatterns = [ path('admin/', admin.site.urls) ] What I'm shooting for is, given an app myapp, instead of having to navigate to mysite.com/admin and then mysite.com/admin/myapp, being able to, on admin sign in, navigate directly to mysite.com/admin/myapp masked as mysite.com/myapp. Also, if it's any help, myapp here is actually django-filer, though I figured how small that community is, there wouldn't be much help gained from making it a filer-specific question. -
Django. How can I render a class method?
I apologize for the stupid question. This is my very first experience with OOP. Question 1: How can I render the value, which is calculated in my class method fseries(self)? I understand that the problem is with parenthesis. I have a number of similar calculated values, which need to be rendered. Shall I calculate / define all these values in class methods or somehow else? Question 2: Is it correct that I am getting the object via get_object_or_404(afc_series, valuefg = self.series) or shall I use another construction? #views.py ... myfilter = Ksf_filter(name="mysuperfilter_XXX", series="ABCDE") #just testing correctness print(myfilter.name) print(myfilter.fseries()) print(myfilter.fseries().valueecp) context = {'myfilter':myfilter,} return render(request, 'af/size/01_kss_size2.html', context) #ksf_filter.py from af.models import afc_series from django.shortcuts import get_object_or_404 class Ksf_filter: def __init__(self, name, series): self.name = name self.series = series def fseries(self): return get_object_or_404(afc_series, valuefg = self.series) #template.html {{myfilter.name}} ///// {{myfilter.fseries()}} //// {{myfilter.fseries().valueecp}}) This is the error message, I get. #Error_msg TemplateSyntaxError at /ru/af/n01_size_kss/ Could not parse the remainder: '()' from 'myfilter.fseries()' Request Method: POST Request URL: http://127.0.0.1:5000/ru/af/n01_size_kss/ Django Version: 3.0.5 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '()' from 'myfilter.fseries()' Thank you -
Django: No Reverse Match... with arguments '('',)' not found, (URL breaks),
PROBLEM: When the user is enrolled in the class (completed shopping cart), the url to the details page doesn't work. When the user is enrolled the url does works. For example: http://127.0.0.1:8000/courses/<COURSE NAME>/view works when not enrolled but not when enrolled. ERROR WHEN ENROLLED "NoReverseMatch at /courses/charting-for-power Reverse for 'course-lessons' with arguments '('',)' not found. 1 pattern(s) tried: ['users/my\\-courses/(?P<slug>[-a-zA-Z0-9_]+)/view$']" THIS IS THE LINK: <a href="{% url 'courses:course-details' enroll.course.slug %}" class="btn">Course Details</a> FROM URLS.PY urlpatterns = [ path('courses/<slug:slug>', CourseDetailView.as_view(), name='course-details'), ] FROM VIEWS.PY class CourseDetailView(DetailView): model = Course template_name = 'courses/details.html' context_object_name = 'course' def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() slug = self.kwargs.get(self.slug_url_kwarg) slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404("No %(verbose_name)s found matching the query" % {'verbose_name': self.model._meta.verbose_name}) return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) course = self.get_object(self.get_queryset()) if self.request.user.is_authenticated: if Enroll.objects.filter(course=course, user_id=self.request.user.id).exists(): context['is_enrolled'] = True else: cart = Cart(self.request) context['is_in_cart'] = cart.has_course(course) else: cart = Cart(self.request) context['is_in_cart'] = cart.has_course(course) return context FROM MODELS.PY from django.db import models from django.utils.timezone import now from accounts.models import User from courses.models import Course class Enroll(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, β¦ -
Regex pattern matching in a JsonField which is a list Django
My jsonfield looks like this: data: [ { key1: "some value", key2: 20202 }, { key1: "some value", key2: 20202 }, { key1: "some value", key2: 20202 } ] Now I want to do regex pattern matching on key1(s) of the data field. How can I do this with Django filter? for regex this question covers things: Django filter with regex any suggestion, StackOverflow reference will help, thanks -
Django oscar docker: AttributeError: module 'os' has no attribute 'uname'
i used git clone https://github.com/django-oscar/django-oscar, then i used pipenv install and i got AttributeError: module 'os' has no attribute 'uname' this error as well as this pipenv.patched.notpip._internal.exceptions.InstallationError: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I am using windows 10. -
Django not reading JSON data passed through AJAX post request
I am sending an AJAX POST request using the following code (submitData is a JS Map): var final_json_data = JSON.stringify(submitData); $.ajax({ type: 'POST', url: POST_URL, data: { 'new-order-details': final_json_data }, dataType: 'json' }); The view for this AJAX request is : def post(self,request): new_order_details = request.body new_order_details = json.loads(new_order_details) return render(request,'home.html') The error showing in python is : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) What could be the error ? Thanks for any help ! -
How to save html table data that has multiple rows and columns to the database?
I need a code to save my form data on button click into the database through views. I am new to Django framework. Can anyone give an idea to save the data from the below table to the database? Below image is for the table that I am using to store my data. -
Django REST: Serializer create function request.user not found
The create function is giving me the following error: AttributeError: 'dict' object has no attribute 'user' Looks like request.user does not exist in this serializer. Is there a way to retrieve the user id in serializer? Or is this not possible? class EmployeeQuestionSerializer(serializers.ModelSerializer): class Meta: model = EmployeeQuestion fields = ( 'id', 'employee', 'question', 'attempted', 'passed', ) def create(self, request): serializer = EmployeeQuestionSerializer(employee=request.user.pk) if serializer.is_valid(): return serializer.save(); def update(self, instance, validated_data): instance.attempted = validated_data.get('attempted') instance.passed = validated_data.get('passed') instance.save() return instance -
How to get React form input values into Django view
What is best way to get certain field input value from React form and put it into django view. I use mail sender that sends mail to one email address after you fill in the form. I would like to know how to contain user inputted values in that mail. So here is my django view that is responsible for sending mails after submitting form: @csrf_exempt def send(request): if request.method == "POST": send_mail('Hello 1', 'testing1', 'austin.roose1@gmail.com', ['lowoko9513@gomail4.com',], fail_silently=False) return redirect('/api/') in that view i would like to exchange 'testing1' with username that comes from form input and also i would like to exchange austin.roose1@gmail.com with user inputed email address. Here is also my React form code: constructor(props) { super(props); this.state = { name: '', email: '', } } handleSubmit(e) { e.preventDefault(); console.log(this.state); axios({ method: "POST", url:'http://127.0.0.1:8000/api/send', data: this.state }).then((response)=>{ if (response.data.status === 'success'){ alert("Message Sent."); this.resetForm() }else if(response.data.status === 'fail'){ alert("Message failed to send.") } }) }; render() { return ( <div> <Form name="normal_login" className="login-form" onSubmitCapture={this.handleSubmit.bind(this)} method="POST" > <Form.Item name="Name" rules={[ { required: true, message: 'Please input your Full name!', }, ]} > <Input prefix={<UserOutlined className="site-form-item-icon" />} value={this.state.name} onChange={this.onNameChange.bind(this)} placeholder="Full name" /> </Form.Item> <Form.Item name="Email" rules={[ { type: 'email', required: β¦ -
DJango python project 1 search wiki
with this code def search(request): entries = util.list_entries() find_entries = list() search_box = request.POST.get("q", "").capitalize() if search_box in entries: return HttpResponseRedirect(f"wiki/{search_box}") for entry in entries: if search_box in entry: find_entries.append(entry) else: print(f'{find_entries}') if find_entries: return render(request, "encyclopedia/search.html", { "search_result": find_entries, "search": search_box }) This all works for my list as follows: CSS Django Git HTML Python Except when I put CSS or HTML in search box. Then i get this error: ValueError at /search The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. Please help -
Mocking requests.get() doesn't seem to work in my unit test for customized Django management command
I have a customized Django management command, sync_users, that I would like to write a unit test for. The sync_users command contacts to my company's HR database via a REST API. So in my unit test I need to set up mock responses. Here is what I have tried: from unittest.mock import Mock, patch ... class TestSyncUsersWithHRAPI(TestCase): @patch('myapp.management.commands.sync_users.requests.get') def test_import_overrun(self, mock_get): get_mocks = [] mock_request_response = { 'data': { '_metadata': { 'links': { 'next': '/data/worker/?page=2&size=10', 'prev': None }, 'page': 1, 'size': 10, 'total': 508718}, 'results': [ { 'user_id': 'mneutron', 'person_first_name': 'Mister', 'person_full_name': 'Mister Neutron', 'person_last_name': 'Neutron', 'person_middle_name': None, 'status': 'EMPLOYEE'}, { 'user_id': 'mentity', 'person_first_name': 'Missus', 'person_full_name': 'Missus Entity', 'person_last_name': 'Entity', 'person_middle_name': None, 'status': 'EMPLOYEE'} ] }, 'status': 'success' } mock_response = Mock() mock_response.json.return_value = mock_request_response mock_response.status_code = status.HTTP_200_OK get_mocks.append(mock_response) mock_get.side_effects = get_mocks call_command('sync_users') When I run my unit test it just seems to run forever. If I run in the debugger I can see that I am not getting what I expected from the "mocked" requests.get() method. Here is the code where I am calling requests.get(...): def get_user_data(self, page=1): if not self.__bearer_token: self.get_token() ... OAuth2 stuff that is working ... response = requests.get(url, headers=headers, verify=False) json = response.json() # <===== β¦ -
Best way to store multiple user-inputted values (port numbers) in Django?
I'm new to Django and database operations and somewhat intermediate with Python. I'm building a web app in Django where the user inputs a port number (values between 1 - 65535), but can input multiple port numbers. I'm using the default SQLite DB. The pseudocode is as follows: User enters a valid port number and hits enter The port number is assigned to the model and field name (e.g., outbound_firewall_ports) and is reflected in the web app The user can continue entering additional port number if needed I have the following field assigned to my class' model: outbound_firewall_ports = models.PositiveIntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(65535)]) Is the best way to get this done using the code above, in combination with forms/views/widgets, or is there another option I should use to essentially create an array from the outbound_firewall_ports that are then stored in the SQLite DB? -
How to insert multiple images in the Django blog app?
What I want is similar to the stack overflow posts, I can add images in between the text, just simply copy the image and paste it in my blog while editing. is it possible? I.ve seen some posts that can add a single image as post cover or add the designated number of images like 'must insert 3 images in a post'. that's not what I want. -
cant load static file in django
I copied a nice html page with lots of images and js... I created the static folder and did everything that is needed, and when I'm tying to load the source with static tag such as: "" I'm still getting an error: GET http://127.0.0.1:8000/static/styles/bootstrap4/bootstrap.min.css net::ERR_ABORTED 404 (Not Found) all it did is to add static in the url and I dont understand why? also I cant to find how to load jinja in pycharm so my tags are white. thanks from advance to all the helpers! -
'ascii' codec can't encode character '\u0661' in position 83: ordinal not in range(128)
I designed a website using django mezzanine platform and it goes completely alright. I just have a problem with utf-8 numbers which I used in pages (actually persian numbers). you see, in django templates it shows numbers as english digits, and when I wanted to show numbers in persian(utf-8) i had to use a custom template tag, which transform all numericals into persian. (I provided the code). but in mezzanine templates it also had to use another custom template tag which implements html tags in WYSIWYG editor. my problem is when I want to combine these 2 template tags it breaks. especially when the page has image in it. consider the "richtext_filters" use the width and height provided by string, and the numbers before getting to them has changed to utf-8 digits, and then the error I entered as the title appears: 'ascii' codec can't encode character '\u06f1' in position 83: ordinal not in range(128) or the other error: Access was attempted on a file that contains unicode characters in its path, but somehow the current locale does not support utf-8. You may need to set 'LC_ALL' to a correct value, eg: 'en_US.UTF-8'. I also considered changing "locale" on my β¦ -
request.FILES returns InMemoryUploadedFile
i made an api to upload file. I have used Django and jQuery.ajax for that. I dont know how to read File this is my views.py file which recieves request def upload(request): if request.method == 'POST': print(request.FILES['image'].file) data = request.FILES['image'].file.read() print(type(data)) print(data) # data.encode() return JsonResponse(data={'message': 'recieved'}) and this is my HTML file from where i am sending file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <form id="form"> {% csrf_token %} <input type="file" id="inp-fld"> <button type="submit">....</button> </form> </body> <script type="text/javascript"> const csrftoken = getCookie('csrftoken'); jQuery.noConflict(); formdata = new FormData(); jQuery("#inp-fld").on("change", function() { var file = this.files[0]; if (formdata) { formdata.append("image", file); console.log(formdata) jQuery.ajax({ beforeSend: function(xhr){ xhr.setRequestHeader('X-CSRFToken', csrftoken) }, url: "/upload", type: "POST", data: formdata, processData: false, contentType: false, success:function(data){ console.log(data) } }); } }); function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } </script> </html> i currently have 0 β¦ -
django or react ,what should i learn for full stack development?
why should i learn django over reactjs for full stack development.Or shouldn't I? I'm just confused . really need the answer . Any good suggestion will be appreciated . -
Django: MultiValueDictKeyError
I created this sign up form which is working perfectly fine. On the same template I created a login form. The sign up form has 3 parameters email, username and password while the login form has only username and password inputs. When I try to sign up everything works fine but when I try to login, it gives me MultiValueDictKeyError Here's my views.py from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError # Create your views here. def usersignup(request): if request.method == 'GET': return render(request, 'social_media/user.html') else: try: user = User.objects.create_user(username=request.POST['username'], password=request.POST['password'], email=request.POST['email']) user.save() login(request, user) return render(request, 'social_media/base.html') except IntegrityError: return render(request, 'social_media/user.html', {'error':'User already exists'}) def loginuser(request): if request.method == 'GET': return render(request, 'social_media/user.html') else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is none: return render(request, 'social_media/user.html', {'errorsignin':'Invalid User man'}) else: login(request, user) return render(request, 'social_media/base.html') Here's my HTML form: {% load static %} <form action="" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="email" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit">Sign In</button> </form> <form action="" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="email" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit">Sign Up</button> </form> Is β¦ -
Can I import a function from a file in a folder with Django as I would do with the models or views?
In Django 3.0, instead of putting all your models in a single models.py file like usual: my_project/ βββ my_project/ βββ my_app/ βββ models.py ... You can create a models/ folder and put each model in a separate file and call normally after adding it to an __init__.py file. my_project/ βββ my_project/ βββ my_app/ βββ models/ β βββ __init__.py β βββ my_models_file.py β βββ my_other_models_file.py ... The models/__init__.py should look like something like this: from .my_models_file import * from .my_other_models_file import * And my models.MyExampleModel in my my_models.py can be called normally in my other files like this: from .models import MyExampleModel # My code This is also possible with the views. Here is my question: Is it possible to proceed the same way with non-Django related files ? I have several functions in my views.py which are not views. They don't render anything. These are simple python functions used to make some of them reusable. # My imports # My view rendering something def my_function(arg): # Do something def my_other_function(arg): # Do something I would like to put them in a folder and put each function in a separate file. Having something like this: my_project/ βββ my_project/ βββ my_app/ βββ β¦ -
How to add a loader to the following Django website (Python)?
The hi.html takes the data and the views.py process the data sending the result to result.html which takes much time to load, till the page is loaded full I want to load a loader or any Gif to make it interactive. Views.py from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.shortcuts import render from demoapp.flipkart import * from demoapp.amzsel import * # Create your views here. def hi(request): return render(request, 'demoapp/hi.html', {}) def search(request): del extractedflip[:] del extractedaz[:] hello = request.GET.get('search') initialflipkart(hello) initialaz(hello) datamatch=zip(extractedaz, extractedflip) context = {'datamatch': datamatch} return render(request, 'demoapp/result.html', context) result.html <div class="container12"> {% for ab in datamatch %} {% for c in ab %} {% for a in c %} <div class="col-xs-12 col-md-6"> <!-- First product box start here--> <div class="prod-info-main prod-wrap clearfix"> <div class="row"> <div class="col-md-5 col-sm-12 col-xs-12"> <div class="product-image"> <img src="{{ a.imglink }}" class="img-responsive"> <span class="tag2 hot"> {{ a.SITE }} </span> </div> </div> <div class="col-md-7 col-sm-12 col-xs-12"> <div class="product-deatil"> <h5 class="name"> <a href="{{ a.link }}"> {{ a.name}} </a> <a href="{{ a.link }}"> <span></span> </a> </h5> <p class="price-container"> <span>βΉ{{ a.price }}</span> </p> <span class="tag1"></span> </div> <div class="description"> <p></p> </div> <div class="product-info smart-form"> <div class="row"> <div class="col-md-12"> <a href="{{ a.link }}" β¦ -
How to update SQLite with no access to a C compiler or yum in a remote server?
I am trying to host a Django (v. 2.2.14) website on Hostgator. However, Django complains about the SQLite version: django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.6.20). I have no access to yum in order to update SQLite: CRITICAL:yum.cli:Config Error: Error accessing file for config file:///etc/yum.conf I tried to compile it from the source code, but I have no access to any C compiler. This is what happens when I try to run ./configure: checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... gawk checking whether make sets $(MAKE)... yes checking for style of include used by make... GNU checking for gcc... no checking for cc... no checking for cl.exe... no configure: error: no acceptable C compiler found in $PATH See `config.log' for more details. And this happens when trying to use gcc (because the plan the company I work for bought has no access to C.): bash: /usr/bin/gcc: Permission denied I need to use Django and I need to use this plan from Hostgator. Is there a way for me to compile gcc or SQLite 3.8.3 on my machine and then just send the files to the remote server? Or β¦ -
Update field value through reverse relationship. Django REST
I am using djangorestframework-simplejwt for authentication. My use case requires me to use OTP instead of passwords. To store OTPs, I have created the following model: class OneTimePassword(models.Model): otp = models.IntegerField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) User model: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) country_code = models.IntegerField(default=91, max_length=3) mobile = models.IntegerField(max_length=11, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile'] objects = CustomUserManager() def __str__(self): return f"{self.email},{self.mobile}" My plan is: POST mobile to /api/generate_otp/ endpoint Inside the view for this endpoint, a new OTP is generated and stored at OneTimePassword model. (the user is determined from mobile number) At the api/token/obtain/ endpoint, OTP and mobile number is posted. If OTP matches the value stored in the OTP model, then JWT token is returned. I am facing difficulty in step 2, i.e. I am not able to update the value of OTP in OneTimePassword Model through the user. I have tried the following approach: class GenerateOTPMobileView(APIView): permission_classes = () def post(self, request,): mobile = request.data.get("mobile") user = User.objects.get(mobile=mobile) random_otp = randint(10000, 99999) if user: user.onetimepassword_set.otp = random_otp # This is not working ... # send OTP through third party API ... return Response({"success": "OTP sent to mobile β¦