Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When tested http POST with chrome POSTMAN, it doesn't work in django

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)

POSTMAN : enter image description here

I tried Django CSRF Cookie Not Set but I think this post is for past version.

like image 642
user3595632 Avatar asked Feb 07 '23 14:02

user3595632


2 Answers

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

like image 81
gidiei Avatar answered Feb 09 '23 04:02

gidiei


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

like image 45
Ivan Semochkin Avatar answered Feb 09 '23 02:02

Ivan Semochkin