Hi i am making an webserver , In which I have to hit some request from html page and return the response. The URL which is generated using html is
http://192.168.2.253:8080/searchSMS/?KPImsgId=0&circle=&subId=&startDate=DD-MM-YYYY&endDate=DD-MM-YYYY&Username=ashish
but in the server side I am not able to see the request data. I am using
q = QueryDict(request.body) but it is showing <QueryDict: {}>
How to find the all the parameters coming in request.
In your case you send the data in url so access the data through request.GET as follow:
username = request.GET.get('Username')
start_date = request.GET.get('startDate')
# ... the same for all the other parameter after the `?` marque.
In fact there is a difference between request data, request.body, request.GET and request.POST:
If you are sending POST request to django function view or class based view: you access the request data in request.body or request.POST.
If you are sending POST request to Django REST Framework: you access the data in request.data. You may also find in Internet request.DATA that correct but it's deprecated in the newer version of DRF in favor of request.data.
If you send parameter in the url like in you case, you access the data form request.GET as explained above.
Related
Im building a simple api in Django Rest Framework using class based views and the documentation mentions request.data (https://www.django-rest-framework.org/tutorial/2-requests-and-responses/)
from rest_framework.views import APIView
class myView(APIView):
def post(self, request):
print(request.data)
When I try to send post requests either with
curl: curl --data param1=val1¶m2=val2 url
djangos browser interface with post (using formatted url and the post option
Advanced Rest Client (chrome add on)
The data of all three appears to end up in request.query_params.
When I try to print request.data, however I get an empty response {}
I could just use request.query_params, Im just curious as to how one would get data to go to request.data since it is talked about in the documentation
edit: so curl --data param1=val1¶m2=val2 -X POST url sends information to request.data (now if I say request.query_params if get the empty dict {} but request.data contains an object that is the dict query_params.)
curl request doesn't have the -X and POST added.
Add these
I am building a REST API server that handles POST requests. The content type in the request is "application/x-www-form-urlencoded".In the request body, we are sending "data1" (some string) and "image" ( a file)
Here's the sample inputForm code I have:
from django import forms
class RequestForm(forms.Form):
data1= forms.CharField(label='data1',max_length=10000)
image = forms.ImageField()
I then validate the content in the form request:
if request.method == 'POST':
form = RequestForm(request.POST)
print("Form content: {0}".format(form))
if form.is_valid():
print("Works")
else:
print("Issue")
Now, when I send the above mentioned data, I always get an error. It prints "Issue". In addition, the line taht prints form content shows it as an error. Something like:
<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="data1" maxlength="10000"
One interesting point: if I remove "Content-type" from the request header, it works.
Any inputs on how I can read the form data correctly when we use content type as application/x-www-form-urlencoded.
thanks in advance...
As per Django Forms documentation:
By default, each Field class assumes the value is required, so if you pass an empty value – either None or the empty string ("") – then clean() will raise a ValidationError exception
You are on the right track, you should send the form as multipart/form-data as per this thread: Thread about form Content types
Found the solution. To begin with, I am sending a file in the input. So I should use content type as "multipart-formdata".
In addition, I am using Postman to pump in the REST API requests. In the body of the request, I set form-data which automatically sets the headers correctly based on what I am sending in the body. I was trying to override it with my own header which is not right.
When I resent my http POST request with no headers in Postman, it worked. (of course, I did verify the final http request itself and confirmed Postman is setting the header correctly)
Im using DJango REST framework to write my web service layer in which I want to read request payload from the request (POST). I tried the following code but I get empty set
#api_view(['POST'])
def login(request):
print request.POST
Content Type is JSON. I tried to pass data from REST Client Tool. Still am able to read header values but only Payload is not coming out.
You should use request.DATA instead of request.POST to retrieve json data.
request.DATA has been deprecated in favor of request.data since version 3.0, and has been fully removed as of version 3.2.
Django request handler let you get POST parameters using request.DATA
def post(self, request):
request.DATA.
How could I get DELETE parameters?
I tried
def delete(self,request):
request.body
request.read()
Both request.body and request.read() just displays csrfmiddlewaretoken and _method parameters.
For both of the above example I am sending the parameters as application/json.
How could I get the delete request parameters?
I know this question is quite old, but for reference: I think you might want Request.QUERY_PARAMS. See the REST Framework docs for more info: http://django-rest-framework.org/api-guide/requests.html
I've been trying to integrate a payment gateway into my site in django.
I'm having trouble getting the response data from the payment gateway.
The payment gateway has sample docs for php which looks like this :
$ErrorTx = isset($_POST['Error']) ? $_POST['Error'] : ''; //Error Number
$ErrorResult = isset($_POST['ErrorText']) ? $_POST['ErrorText'] : ''; //Error message
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''; //Payment Id
In the view for the url that the payment gateway is redirecting to after entering card details etc, I'm checking if it's a GET if request.method == "GET" and then passing the request to a function. When I debug the request, I can see an empty query dict. and if I try something like res = request.GET['paymentid'] I get an error that says there's no key called paymentid.
Am I missing something obvious? I'm still pretty new to django, so I'm sure I'm doing something wrong.
res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.
Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get() method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
You should have access to the POST dictionary on the request object.
for class based views, try this:
class YourApiView(generics.ListAPIView):
"""
API endpoint
"""
def post(self, request, *args, **kwargs):
print("request data")
print(request.data)