django 请求

返回json数据格式

from json import dumps
......
@csrf_exempt
def createPosting(request):
    if request.method == 'POST':
        try:
            title=request.POST['title']
            req={'message':'发帖成功','title':title}
            return HttpResponse(dumps(req),content_type="application/json")
        except:
            req={'message':'发帖失败'}
            return HttpResponse(dumps(req),content_type="application/json")

django post 请求 403

在开头添加

from django.views.decorators.csrf import csrf_exempt

在使用POST的函数前添加@csrf_exempt

示例

from django.shortcuts import render
from django.http import HttpResponse
from .models import Post,Comment
from django.views.decorators.csrf import csrf_exempt


def index(request):
    html = "

index

" return HttpResponse(html) @csrf_exempt def getPostByTitle(request,postTitle): if request.method == 'GET': post=Post.GetPost(title=postTitle) if post=='查询错误': html='查询错误' return HttpResponse(html) comment = post.comment_set.all() #评论集 comment = comment.order_by('-createDate') #按照发送时间排序 data={ 'post':post, 'comment':comment } return render(request, 'posting/post.html', data) elif request.method == 'POST': return HttpResponse('请求成功')

现在使用POST方式调用该函数可得到返回 请求成功

你可能感兴趣的:(django 请求)