一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

django在接受post请求时显示403forbidden的教程

时间:2018-01-26 编辑:猪哥 来源:一聚教程网

本文介绍了是django在接受post请求时显示403forbidden时的处理方法,小编分享给大家,供大家参考

最近在做一个项目需要用到Django框架

在测试Django的时候发现一个问题,就是按照一般教程设置好URL的mapping之后,使用get请求总能得到正确的回应,但是在使用post请求时,却根本无法得到请求,会显示403forbidden:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Forbidden (CSRF cookie not set.): /
[23/Mar/2017 20:58:36] "POST / HTTP/1.1" 403 2857

根据提示(CSRF cookie not set)上网搜索了一下,发现只要在接收post请求的函数前加上csrf_exempt装饰器就可以了:

# coding=utf-8

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json


# Create your views here.
@csrf_exempt
def index(request):
  if request.method == 'POST':
    body = json.loads(request.body)
    print body['value']
    return HttpResponse(request.body)

控制台输出为(传入的body为{'value': 'test'}):

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
test
[23/Mar/2017 21:03:37] "POST / HTTP/1.1" 200 17

热门栏目