Differing Reponse Codes from Django Application - python

For both GET and POST requests I simply want to print the associated QueryDict in my test view:
if request.method == 'GET':
print request.GET
if request.method == 'POST':
print request.POST
When I make requests using both methods I get different response codes. I could use some help.

The post request has triggered Django's CSRF protection so you are getting a 403 Forbidden response.
Usually, it means that you need to include the CSRF template in your template.
In this case, because you are making requests from the shell, it might be appropriate to use the csrf_exempt decorator on this view to disable the CSRF protection.

Related

how to implement csrf without csrf token in django

In django, if I want to use csrf token, I need to imbed a form with csrf token in django template. However as a backend-engineer I am co-working with a front-end engineer whose code is not available for me. So I caanot use the template. In this case, if I want still the csrf function. what should I do?
you should ask the coworker to embed the csrf token in the form he is sending you
you can get it from document.Cookies if he doesnt want to or cannot use the {% csrf %} tag
You may use #csrf_exempt decorator to except csrf tokens.
First, import decorator
from django.views.decorators.csrf import csrf_exempt
Then add #csrf_exempt before your view.
#csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
More details can be found here enter link description here

A simple question about POST and GET request

I just started to learn Django by following a sentdex tutorial. During the course, we added a User model into our database and we created a function in our views.py file:
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():#si les champs sont OK :
user = form.save()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
print(form.error_messages[msg])
But in this piece of code, I don't understand how Django knows if the request.method is True or False. Is it because I created a form with a Submit button in my template ?
Its impossible to say exactly what happens in your case since we don't have your HTML but in general:
When you create an HTML form, you can specify a method as follows <form method="POST"></form> or <form method="GET"></form>. If you don't specify the default is GET.
When you submit your form, it sends the data using an http request of the specified type. This is what Django is reading.
In this case, request.method simply represents the HTTP method that was used to access your view. For example, your register function might be assigned a url configuration such as: url(r'^register/', views.register), which maps an incoming HTTP request to your view. If you have a web form with a 'Submit' button, it's likely the web application code is submitting an HTTP POST request to your web server.
Django automatically constructs the request object for you, so you can check in your view how the request was made against the web server. For more info about what other things are included in the request, check the Django docs.

Check if user is authenticated with django TokenAuthentication

I'm trying to develop a REST API with DRF that uses TokenAuthentication. This will be used in an android app.
I was able to authenticate a user and retrieve it's token. The problem I'm having now is with the following view:
#csrf_exempt
def foo(request):
if request.method == 'GET':
if request.user.is_authenticated():
...
do stuff
...
return HttpResponse(data, "application/json")
else:
return HttpResponse(status=401)
Basically the user should be authenticated in order to receive the data, otherwise, he will receive a 401 response.
I'm making a GET request to the proper URL with the following parameters in the Header:
content-type : application/json
authorization : Token <user token>
Which is basically what I'm doing for other Viewsets (this is not a Viewset) I have - and it works.
In this case, it's always sending the HTTP response with 401 code (user isn't authenticated).
I can't figure out if the problem is with the Header values I'm passing or if this is not the proper way to check if the user is authenticated.
Edit: if I do: "print request.user" i get AnonymousUser
Thanks!
Solved
As suggested by "ABDUL NIYAS P M" I used the APIView
Basically, I just added the #api_view(['GET']) decorator to the View.
#csrf_exempt
#api_view(['GET'])
#permission_classes((IsAuthenticated, ))
def foo(request):
if request.method == 'GET':
...
An easier way to do this is by checking if the user session is existing or not.
When DRF creates a token, it also creates the session cookie.
return HttpResponse(json.dumps({"is_authenticated": True if request.session.get('_auth_user_id', 0) else False}),
content_type='application/json')

How to get HTTP POST parameters in exact order in Django?

I am trying to get the POST data parameters in the exact order they are received in Django.
I have this in my views.py:
#require_POST
#csrf_exempt
def paypal_ipn_listener(request):
print request.POST
print request.body
The data in request.POST is in QueryDict which is unordered, thus doesn't suit my needs.
Trying to access request.body throws an exception:
RawPostDataException: You cannot access body after reading from request's data stream
I think this exception happens because of my #require_POST or #csrf_exempt decorators which perhaps call some middleware which reads POST data stream.
Anyway my question is how do I get HTTP request POST data in exact order?
I need to keep the order to satisfy PayPal IPN implementation requirements.
** UPDATE **
I ended up manually parsing request.body since there is no better solution.
What if you delete #require_POST and do something like this?:
from django.http import Http404
#csrf_exempt
def paypal_ipn_listener(request):
if request.method != 'POST':
raise Http404('some error')
print request.body

Clear POST in web page

I have a small python/django web site and I'm using a html form POST some information, annoyingly however this information is stored in POST so when a user refreshes in say IE/chrome they get that warning message about the page containing POST data. How do I clear the POST data after it has been processed so a user can refresh and not see this warning message?
Also I have some logic as follows that detects a POST
if request.method == "POST":
do something
Select all
Open in new window
This is fine when I actually post the form, but when I refresh the page it also detects the POST and does the logic that I now dont want to do.
How can I solve this also??
Thanks
After form is validated and it is valid. Then do the redirect to some other page e.g. a success page or redirect to the same view. The redirection will avoid Double Form Submition problem. Read more about it here.
Use HttpResponseRedirect when you return the response for POST request. This is explained in tutorial 4 as
After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).
As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn't specific to Django; it's just good Web development practice.
As Rohan said, you should use HttpResponseRedirect. But also you can use a shortcut:
from django.shortcuts import redirect
def some_view(request):
if request.method == 'POST':
# do smth
return redirect('/page-with-form/')

Categories