Reputation: 5730
I use Django 1.9.7 & Python 3.5
I implement creating user mechanism and tried to test with POSTMAN(chrome application), but it doesn't work and it shows something like belows:
Forbidden (CSRF cookie not set.): /timeline/user/create/
This is the code :
urls.py
from django.conf.urls import url
From. import views
app_name = 'timeline'
urlpatterns = [
# ex) /
url(r'^$', views.timeline_view, name='timeline_view'),
# ex) /user/create
url(r'^user/(?P<method>create)/$', views.user_view, name='user_view'),
]
views.py
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, HttpResponse
from timeline.models import *
def timeline_view(request):
return HttpResponse('hello world')
def user_view(request, method):
if method == 'create' and request.method == 'POST':
print("hi")
username = request.POST.get('username')
username = request.POST.get('username')
user = User.objects.create_user(username, password=password)
user.first_name = request.POST.get('name','')
user.save()
profile = UserProfile()
profile.user = user
profile.save()
return HttpResponse('create success')
else:
return HttpResponse('bad request', status=400)
I tried Django CSRF Cookie Not Set but I think this post is for past version.
Upvotes: 4
Views: 10986
Reputation: 47
Use this below statement on top of each and every view function definition (views.py). We don't need to use CRF related statements.
from rest_framework.decorators import api_view
@api_view(["POST", "GET"])
eg:
@api_view(["POST", "GET"])
def GivenInput():
return Response(e.args[0],status.HTTP_400_BAD_REQUEST)
Note*: But I didn't know that any alternative way to make it global throughout the file.
Upvotes: 0
Reputation: 527
Sometimes Version problem in 'Postman' :
I have face the same problem. While sending the data using the oldest version of postman in POST method.
That time I have received the empty json data in server side.
And I have fix this problem, Once I uninstall the oldest version of postman and installed with latest version.
Upvotes: 1
Reputation: 79
for testing i used the @csrf_exempt decorator.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def user_view(request, method):
...
now you should be able to call this function without the csrf cookie.
(last time i tried it, i was using django 1.8.7)
source: https://docs.djangoproject.com/en/1.9/ref/csrf/#edge-cases
Upvotes: 6
Reputation: 8897
You should put CSRFToken
in request headers.
After sending request via postman, look at the response Cookies
section, take csrftoken value and put in Headers
section of request, like this:
key:X-CSRFToken
value: jSdh6c3VAHgLShLEyTjH2N957qCILqmb #your token value
Upvotes: 1