Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make PermissionRequiredMixin also check for object level permission
I am using Django Guardian to have object-level permission along with global permissions. Some of the users have a group with global permissions, and some have object-level permissions. With this, I seem to need to modify the PermissionRequiredMixin to check also for the object-level permission. views.py class MainPageView(PermissionRequiredMixin, TemplateView): permission_required = "app.view_mainpage" template_name = "web/mainpage.html" This one works if the user has global permission but if the user is under a group with object-level permission, it won't. With guardian, to check for object-level permission, you also have to pass the object instance. example: self.request.user.has_perm('view_mainpage', obj) And on PermissionRequiredMixin, the checking goes only like this, self.request.user.has_perms(perms) So if the user has a group with permission of view_mainpage of a specific object, how can I check it too? By the way, all my permissions are of the same content_type. Is there any way I can execute this? Like I have to pass the object instance to PermissionRequiredMixin if the user is under an object-level group and None if the user is under a global group. -
After overriding permissions, endpoint should require a token to access, however it's not
I am using Django REST for my API. Here is my custom permission class: permissions.py: from rest_framework.permissions import BasePermission from rest_framework.response import Response class ItemsPermissions(BasePermission): def has_permission(self, request, view): try: request_data = request.data print(request_data) auth_token = request_data['returnedDataFromAuthAPI'] if("accessToken" in auth_token): auth_token = auth_token['accessToken'] Response({"Permission Granted - AccessToken": auth_token}) return True #else Response({"message": "No Auth Token Provided! You Need To Login!"}) return False except Exception as ex: return Response({"message": ex}) in views.py: class ListItems(generics.ListAPIView): permission_classes = [ShippingPermissions] queryset = myModel.objects.all() serializer_class = mySerializer in urls.py: url_patterns = [ path("/items/list/", ListItems.as_view()), ] I have an authentication microservice that I get the JWT Token from, for the user to have access to the views. In the ItemsPermissions class I am checking the token. My Question: I want to grant the user access to the ListItems class, after the token is provided, but if token is not provided then the user should not have access. However, for some reason, I am able to access the /items/list/ endpoint, and it does not ask me/require a token at all. I am getting No errors. What is the problem ? -
If in Html calling a model
I have this model: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255) month = models.CharField(null=True, blank=True, max_length=255) year = models.IntegerField(null=True, blank=True) def __str__(self): return self.name in html page: when I write {{ canva.month }}, it shows me the value JUNE but when I write: {% if JUIN == canva.month %} hello {% else %} goodbye {% endif %} it always show me goodbye. -
Django don’t redirect to confirmation page when delete
Django don’t redirect to confirmation page when delete. Hi all, I did a standard CRUD on a table, which is foreign key on one other table. I use the Django view class. Create, Read and Update work, but I have a bug on the Delete. When I delete one item, I am redirected to detail page (Read page) with the good delete address (‘localhost/table_name/pk/delete’). I follow the standard way describe in Django Project and in several tutorial. Following, portion of my code: model.py : class Badge(models.Model): id_badge = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) level = models.IntegerField() image_badge = models.ImageField(upload_to='badge_image/', null=True, blank=True, default='ex-par-nat_logo.png') class Meta: managed = True db_table = 'badge' view.py: from django.shortcuts import redirect, render from UsersApp.tribut_sign_up_form import TributSignUpForm from UsersApp.tutor_sign_up_form import TutorSignUpForm from UsersApp.child_sign_up_form import ChildSignUpForm from django.contrib.auth import authenticate, login from django.contrib.auth import logout as account_logout from UsersApp.models import Tribut, Tutor, Child, Account from django.http import HttpResponse from django.contrib.auth.decorators import login_required from UsersApp.decorator import tribut_required @method_decorator([login_required, author_required], name='dispatch') class BadgeListView(ListView): model = Badge ordering = ('title', ) template_name = 'ArticlesApp/badge_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get_queryset(self): queryset = Badge.objects.all() return queryset @method_decorator([login_required, author_required], name='dispatch') class BadgeCreateView(CreateView): model = Badge # form_class … -
django.db.utils.IntegrityError: null value in column COLUMN_id violates not-null constraint
Newbie here both on Stackoverflow as well as django/drf. I am receiving this error, I know that I can solve this by adding the null field in the calendar foreign key file. I can not modify the field due to some reason, how can I fix this. Please let me know if other info is required. Error: django.db.utils.IntegrityError: null value in column "instructor_id" violates not-null constraint Model class Calendar(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) Serializer class CalendarSerializer(serializers.ModelSerializer): class Meta: model = Calendar fields = '__all__' depth = 1 -
should ssh file "ssh_config" always be located in "~/.ssh" folder
I have noticed while learning how to setup ssh that lots of stackoverflow posts referred to the file ssh config being inside of the folder ~/.ssh but when i look at the same folder in my macbook the files listed are: created from my last ssh setup someprivatekey someprivatekey.pub known_hosts now when i inspect the folder cd /etc/ssh/ then i can see the file ssh_config there. Is it a normal behavior or should ssh file "ssh_config" always be located in "~/.ssh" folder and I have presumably a wrong configuration? (Sorry if the post sound very elementary, i am learning how to use ssh) Thanks -
How to deliver image file to python backend with Imgur API when uploading images from React frontend
I am trying to upload image from React frontend and deliver this image object to Django, Python backend, with Imgur API. (imgurpython) My goal is to upload the image to Imgur in Python backend and gets image url from Imgur, finally I will return this url back to React frontend side to use. But I have some problem and confused it how to get this Image File in Django views with request. Here is my frontend page. And there are my codes frontend/Screen import React, {useState,useEffect} from 'react' import { Link } from 'react-router-dom' import { useDispatch, useSelector} from 'react-redux' import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap' import Message from '../components/Message' import { uploadImage } from '../actions/caseActions' function CaseScreen({ match, location, history}) { const dispatch = useDispatch() const [image, setImage] = useState(null) const handleInputChange =(event) =>{ event.preventDefault(); console.log(event) console.log(event.target.files[0]) setImage({ image: event.target.files[0] }); } const uploadImgurImage = (event) => { event.preventDefault(); let data = new FormData(); data.append("image", image); dispatch(uploadImage(data)) // send to actions } return ( <Row> <Col md={8}> <Card>個案頁</Card> <form onSubmit={uploadImgurImage}> <input type="file" name="image" onChange={handleInputChange}/> <button>Submit</button> </form> </Col> </Row> ) } export default CaseScreen frontend/uploadActions import axios from 'axios' import { UPLOAD_IMAGE_REQUEST , UPLOAD_IMAGE_SUCCESS … -
Import xlsx spreadsheet with column index accented - Django Models
My question is that I want to import a spreadsheet, but some columns are with accented names (words in Portuguese) Example: Município Municipio = models.TextField('Município', blank=True, null=True) Consequently, the column is imported without values as the column was not recognized. The only way to solve it would be to change the column names in the spreadsheet to words without accents? -
Django get data from Partition in Model
We are building a website and our system is dynamically partitioned with the architect plugin. Is there any way to look into the partitioned table directly and get data from it with Django Models? Can we pass the table name while filtering or retrieving the data, can I do so? -
Is it possible to make a connection to a ready made server in a Django/Python web app
I have been asked to create a Django Web Application that prints account balances, age analysis', customer statements etc. This program needs to connect to the database at our office (Pastel Evolution Database) and fetch accounts etc. from there. I had previously created this code to connect to the database via .bat: import pymssql user = '[User ]' password = '[Password]' server = '[IP]' #username: [Username]_dev_ro #password: [Password] #database name: DB_Name databaseName = 'DB_Name' conn = pymssql.connect(server, user, password, databaseName) cursor = conn.cursor(as_dict=True) cursor.execute('SELECT top 10 * FROM [DB_Name].[dbo].[_etblGLAccountTypes]') for row in cursor: print(row) conn.close() If anyone knows how I would create the same sort of function inside of Django so that I can fetch the data from the server and print it onto a Web-Page , please assist . -
how to optimize the execution time of a django view so that it does not take time to execute
I need help, my django view is taking a long time to run I have 6 views in total and each view takes 6min of responses i use pandas dataframe to extract xml data then i apply multiple calculation formula, the slowest is when loading the home.html homepage because it takes 45min to run solution I read: -use multiprocessing to execute each view in parallel but I don't know how to do it what I looked for: -django-q, unfortunately this is for sql queries, my code doesn't contain sql queries, Do you have any ideas? of the process that I have to follow my home_view django def home_view(request): month = ''.join(request.GET.getlist('id_mois')) this_region = ''.join(request.GET.getlist('id_region')) # --------------------REVENU-------------------- : from REVENU.revenu import details_revenu init_revenu = initializing_revenu() ref_details_revenu = details_revenu(init_revenu[0], init_revenu[1], this_region, month) # ---------------------SUBSCRIBER------------------: from SUBSCRIBER.subscriber import subscriber_details init_subscriber = initializing_subscriber() ref_subscriber = subscriber_details(init_subscriber[0], init_subscriber[1], this_region, month) # -----------------ANIMATEUR--------------------: from ANIMATEUR.animateur import function_animateur init_animateur = initializing_animateur() ref_animateur = function_animateur(init_animateur[0], init_animateur[1], this_region) # -----------------MVOLA--------------------: from MVOLA.mvola import mvola_details init_mvola = initializing_mvola() mvola = mvola_details(init_mvola[0], init_mvola[1], this_region, month) context = {#....some context} return render(request, 'home.html', context) here returned, subscriber, mvola, animateur takes 6min each time to execute -
Django: Aggregation, force Avg to return integer instead of decimal
is there any way how can I replace this ugly stats['price_avg'] = round(stats['price_avg']) to a better solution? I tried using Round() ORM function, but this returns in X.0 format. What I need is only an integer without any decimals. stats = Ad.objects.aggregate( ads_total=Count('pk'), price_min=Coalesce(Min('price'), Val(0)), price_avg=Coalesce(Avg('price'), Val(0.0)), price_max=Coalesce(Max('price'), Val(0)), ) stats['price_avg'] = round(stats['price_avg']) For example, right now I receive this API payload: { "ads_total": 9, "price_min": 35, "price_avg": 426.1111111111111, "price_max": 1500 } What I want: { "ads_total": 9, "price_min": 35, "price_avg": 426, "price_max": 1500 } -
django orm insert foreignkey via id
I have a Model like class Author(models.Model): book = models.ForeignKey(Book, null=True, blank=True) now, I have a dict in form of: math = {"id": 4, "title": "math book"} right now, the way im inserting data is math_book = Book.objects.query(id=math['id']).first() # im sure the value is there author = Author.objects.first() author.book = math_book im wondering if it's possible to do something like: author.book_id = math['id'] and save the single query to fetch the book? -
Server Error (500) After Django Deployment
This error when I ran "heroku logs --tail" Continuation of the error Here is the Github repo link: https://github.com/rhedwan/HNGi8XI4GStage2to3 -
How to get String value instead of number in foreign key field in django?
Here's my models class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot class jenkinsHistory(models.Model): robotName = models.ForeignKey(Robot, on_delete=models.CASCADE, blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100,blank=True) jenkinsBuildStatus = models.CharField(max_length=200,blank=True) errorMsg = models.CharField(max_length=500,blank=True) Param = models.CharField(max_length=500,blank=True, null=True) def __str__(self): return self.robotName I have assign data in jenkinsHistory table from Robot table. here's the code that how i assign the data def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) hist = jenkinsHistory(robotName= pi,jenkinsBuildStatus='Jenkins-Running') hist.save() now i want to show that data in a table in my UI. so that i have written this view def Robot_History(Request,id): fm = list(jenkinsHistory.objects.values('id','robotName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param').filter(robotName=id)) print("hello",fm) rob = Robot.objects.all() return render(Request, 'hello/robotHistory.html',{'jenkinsHistory': fm,'robot': rob}) and here's my html {% for hist in jenkinsHistory %} <tbody> <tr> <td>{{hist.id}}</td> <td>{{hist.robotName}}</td> <td>{{hist.jenkinsBuildNumber}}</td> <td>{{hist.jenkinsBuildStatus}}</td> <td>{{hist.errorMsg}}</td> <td>{{hist.Param}}</td> </tr> </tbody> {% endfor %} But when i got the data the foreign key field coming as a id not string but in my django admin it is coming as a string only how to solve that issue? -
NoReverseMatch at /account/login/ (Trying to use Class based authentication views)
I am trying to use Django's class based authentication views and am getting the following error when attempting to access the login view: NoReverseMatch at /account/login/ Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Error during template rendering In template /Users/justin/Desktop/Programming/Python/django_book/social/website/account/templates/base.html, error at line 0 All authentication templates are stored at templates/account/registration/ and dashboard.html is stored at account/templates/account/, here is the code: urls.py: from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.dashboard, name = 'dashboard'), path('login/', auth_views.LoginView.as_view(), name = 'login'), path('logout/', auth_views.LogoutView.as_view(), name = 'logout'), ] login.html: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in. If you don't have an account <a href="{% url "register" %}">register here</a></p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> </div> {% endblock %} base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title%}{% … -
jquery.formset.js custom buttons and positions
how can i change the buttons with jquery.formset.js? I would like to put it in the click event for the blue one to create a new empty object to be compiled, while for the red one the elimination of the object. Using those I only get links and if I put the classes I create the button but I can't place it where I want. Can someone help me? image example -
Font Awesome icons don't display in dropdown menu from <select> <option> in Firefox
I'm creating an anime list using Django. You can see this list in the 2-columns table. You can add titles and next to them you can set the status by selecting one of Font Awesome icons in the dropdown menu created by using HTML tags select and option. The problem is when I want to select one of the icons I can't see what icon I choose. Instead of it, there are some squares. The problem appears on Firefox but on Chrome it doesn't exist. Besides the dropdown menu, icons display normally. Part of index.html code: <h2>Legenda:</h2> <ul> <li>Obejrzane/przeczytane: <i class="fas fa-check"></i></li> <li>Nieobejrzane/nieprzeczytane: <i class="fas fa-times"></i></li> <li>Do obejrzenia/przeczytania: <i class="fas fa-flag"></i></li> <li>W trakcie oglądania/czytania: <i class="fas fa-circle"></i></li> </ul> <a href="{% url 'jam_app:new_title' %}">+ Dodaj tytuł</a> <table> <th>Tytuł</th> <th>Status</th> {% for title in titles %} <tr> <td> <a href="{% url 'jam_app:detail' title.id %}">{{ title }}</a> </td> <td> <form action="jam_app:index"> <select class="fa"> <option value="fas fa-check">&#xf00c</option> <option value="fas fa-times">&#xf00d</option> <option value="fas fa-flag">&#xf024</option> <option value="fas fa-circle">&#xf111</option> </select> </form> </td> </tr> {% endfor %} </table> I've found that maybe I should do something with Access-Control-Allow-Origin. I tried to add some code like here in the first answer or download the add-on 'Allow CORS: Access-Control-Allow-Origin' but … -
How can I allow users to update details? I am getting NOT NULL constraint failed
from django.contrib.auth.signals import user_logged_in from django.shortcuts import redirect, render from django.contrib.auth.models import User,auth from django.contrib.auth import authenticate,logout from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def update(request): if request.method=="POST": firstname=request.POST.get('first_name') lastname=request.POST.get('last_name') """email=request.POST.get('email') username=request.POST.get('username')""" #password=request.POST.get('password') cur=request.user print(cur) print('i came till here') user=User.objects.filter(username=cur).update(first_name=firstname,last_name=lastname) user.save() print('i came here') return redirect('profile') else: print('i came to elses block') redirect('index') I want users to update their details but I am getting error when I try to submit "Not null constraint" The problem is only in the update function. Any help will be appreciated. -
2013, 'Lost connection to MySQL server during query' in Django While executing query in MySQL
2013, Lost Connection to MySQL query Getting error while executing query in MySQL. This error is coming while executing MySQL queries from Django framework. Please suggest ways to solve the problem. Already tried with CONN_MAX_AGE property. -
CHANGE VALUE OF FIELD WHEN SUBMITTING ANOTHER FOEM THAT CONTAINS THIS FIELD AS PRIMARY KEY DJANGO
I HAVE TWO CLASSES THE FIRST ONE (CoupeLithologique) HAS A FIELD (ref_coupe) AS PRIMARY KEY THE SECOND ONE (Sondage)HAS IT AS FOREIGN KEY (coupe) I WANT TO CHANGE THE VALUE OF FOREIGN KEY (coupe)WHEN SUBMITTING THE FORM (CoupeLithologiqueModify)OF THE FIRST CLASS (CoupeLithologique) AUTOMATICALLY. ***Models.py:*** class CoupeLithologique(models.Model): ref_coupe = models.CharField(max_length=10, blank=True, null=True) machine_coupe_lithologique = models.CharField(max_length=10, blank=True, null=True) technicien = models.ForeignKey('Technicien', models.DO_NOTHING, blank=True, null=True) class Sondage(models.Model): ref_sondage = models.CharField(max_length=10, blank=True, null=True) profondeur_total_sondage = models.CharField(max_length=10,blank=True, null=True) niveau_piezometrique_sondage = models.CharField(max_length=40, blank=True, null=True) observation_sondage = models.CharField(max_length=30, blank=True, null=True) log_strati = models.ImageField(upload_to='img/bsd_images/',blank=True, null=True) profil_pressio_sondage = models.ImageField(upload_to='img/bsd_images/',blank=True, null=True) projet = models.ForeignKey(Projet, models.DO_NOTHING, related_name='projet',blank=True, null=True) coupe = models.ForeignKey(CoupeLithologique, models.DO_NOTHING,related_name='coupe' ,blank=True, null=True) section = models.ForeignKey(Sections, models.DO_NOTHING, related_name='section',blank=True, null=True) geom = models.PointField(geography=True, default=Point(0.0, 0.0)) class Meta: managed = True db_table = 'sondage' ***Views.py :*** def ajouter_coupe(request): if request.method == "POST": form = CoupeLithologiqueForm(request.POST) if form.is_valid(): form.save() return redirect('/Coupe//Afficher') else: form = CoupeLithologiqueForm() return render(request, 'Ajouter_Coupe.html', {'form': form,'techniciens':Technicien.objects.all()}) ***HTML:*** <div id="form_c" style="width:450px;display:none;"> <h2 style="text-align:center; color: rgba(255,255,255, 0.8) !important;">Modifier Sondage</h2><hr> <form action="{%url 'app_technicien:Ajouter_c'%}" method="POST"> {%csrf_token%} <tr><th><label for="id_ref_coupe">Ref coupe:</label></th><td><input type="text" name="ref_coupe" maxlength="10" id="id_ref_coupe"></td></tr> <tr><th><label for="id_machine_coupe_lithologique">Machine coupe lithologique:</label></th><td><input type="text" name="machine_coupe_lithologique" maxlength="10" id="id_machine_coupe_lithologique"></td></tr> <tr><th><label for="id_technicien">Operateur:</label></th><td><select name="technicien" id="id_technicien"> {% for tech in techniciens %} <option value="{{tech.pk}}" >{{tech.nom_technicien}}</option> {%endfor%} </select></td></tr> <button id="enr" type="submit" name="login" class="btn btn-fill btn-primary" … -
Get the specific details of selected item
I would like to show the selected part's Standard pack value into a non-editable box. I have two models Part (also foreign key in DeliveryIns table) and DeliveryIns and during creating a deliveryins user has to choose a Part name. So after choosing the Part name in DeliveryIns form, I would like to show the Standard pack value of that selected/chosen Part into a box. models.py class Part(models.Model): partno = models.CharField(max_length=50) partname = models.CharField(max_length=50) standardpack = models.PositiveIntegerField(default= 0) def __str__(self): return self.partname views.py def create_deliveryins(request): from django import forms form = DeliveryInsForm() forms = DeliveryInsForm(request.method == 'POST') if forms.is_valid(): di_id = forms.cleaned_data['di_id'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] supplier = forms.cleaned_data['supplier'] q = Part.objects.get(id=part.id) deliveryins = DeliveryIns.objects.create( di_id=di_id, product=product, part=part, supplier=supplier, ) return redirect('dins-list') context = { 'form': form } return render(request, 'store/addDins.html', context) Can anyone help to how to pass the Standard pack value from Parts table after selecting a Parts name in DeliveryIns form? -
Django model's OneToOne relationship - AttributeError: object has no attribute
please help ! I am building a simple maintenance ticketing system. model Ticket captures the initial data. model UpdateTicket enables a responder to update details on the Ticket as well as including additional field for comment and a timestamp. UpdatedTicket has a OneToOne relationship with Ticket but I get an AttributeError: 'Ticket' object has no attribute when I try to access the associated data. (even though in the site admin section the relationships are working fine) Here are the models from django.db import models from django.utils import timezone from django.urls import reverse from members.models import Member class Ticket(models.Model): """ model to represent maintenance issue ticket """ # id = models reporter = models.ForeignKey(Member, on_delete=models.CASCADE, null=True, related_name='+', db_column='reporter') location = models.ForeignKey(Member, on_delete=models.PROTECT, null=True, related_name='+', db_column='location') date_reported = models.DateTimeField(default=timezone.now) description = models.TextField(max_length=100) contractor = models.ForeignKey('Contractor', on_delete=models.PROTECT, null=True) class Meta: ordering = ['date_reported'] permissions = [ ("can_message", "add a new message"), ("can_update", "update a ticket"), ] def __str__(self): """ string to return the model name as text""" return f'{self.reporter}, {self.date_reported} GOTO -> ' def get_absolute_url(self): """Returns the url to access a particular ticket instance.""" return reverse('maintenance-ticket', args=[str(self.id)]) class UpdatedTicket(models.Model): ticket = models.OneToOneField(Ticket, on_delete=models.CASCADE, related_name='_ticket', primary_key=True,) comment = models.TextField(max_length=300, null=True) date_updated = models.DateTimeField(default=timezone.now) class … -
Django reverse foreign key leading to duplicate queries
I'm trying to use ViewSet to return list of all assets with the asset type name (instead of just id) but according to django-debug-toolbar, my queries are being duplicated leading to slower results. 1 Asset type can have multiple assets. So, when I try to retrieve all assets (children) -- it's trying to fetch the asset type (parent) names for each of the assets (children) but it's running one query for every asset (child). Looks something like this: It's duplicated 6 times because I have 6 values in the Asset table currently. QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.99 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.99 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.00 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (29,) 6 similar queries. Duplicated 3 times. … -
getting expected curl output in postman.. but not the same when using django view.py
Im doing payment integration in my website and following curl is from phonepe api docs. While using curl its working but not with request.post method in django Here is the curl: curl --location --request POST 'https://mercury-uat.phonepe.com/v4/debit/' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'X-CALLBACK-URL: https://www.demoMerchant.com/callback' \ --data-raw '{ "merchantId":"M2306160483220675579140", "transactionId":"TX123456789", "merchantUserId":"U123456789", "amount":100, "merchantOrderId":"OD1234", "mobileNumber":"9xxxxxxxxx", "message":"payment for order placed OD1234", "subMerchant":"DemoMerchant", "email":"amit***75@gmail.com", "shortName":"Amit" }' And CurlOutput: { "success": false, "code": "BAD_REQUEST", "message": "Please check the inputs you have provided.", "data": {} } But im doing the same thing in django view.py im getting empty dictionary in output Here is code: class test(generics.GenericAPIView): def post(self, request): url = "https://mercury-uat.phonepe.com/v4/debit/" headers = { "Accept": "application/json", "Content-Type": "application/json", "X-CALLBACK-URL": "https://www.demoMerchant.com/callback" } data = { "merchantId":"M2306160483220675579140", "transactionId":"TX123456789", "merchantUserId":"U123456789", "amount":100, "merchantOrderId":"OD1234", "mobileNumber":"9xxxxxxxxx", "message":"payment for order placed OD1234", "subMerchant":"DemoMerchant", "email":"amit***75@gmail.com", "shortName":"Amit" } response = requests.post(url, data=data, headers=headers).json() print(response) return Response(response) output: {}