django - 为什么 csfr 豁免装饰器不起作用?
问题描述
我正在尝试从 AJAXfetch
向带有@csfr_exempt
装饰器的 Django 视图发送“POST”请求,但仍然出现403 Forbidden (CSRF token missing or incorrect.): /profile/follow
错误。有人可以解释为什么吗?(这里是新手)。
这是.js
:
function follow_user(user, follower, action) {
fetch(`follow`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: user,
follower: follower,
action: action
})
})
.then(response => response.json())
.then(data => {
document.querySelector("#followers-count").innerHTML = `Followers: ${data.followers}`
});
console.log(console.log(`Schiscia: ${follower} ${action} ${user} ${data.followers}`));
观点是:
@csrf_exempt
def follow(request):
if request.method == "POST":
user = request.POST.get('user')
follower = request.POST.get('follow')
action = request.POST.get('action')
target = User.objects.get(username=user)
sourceusr = User.objects.get(username=follower)
if action == 'follow':
target.followers.append(sourceusr)
sourceusr.following.append(target)
return JsonResponse({'Following': target.following}, safe=False,
status=201)
解决方案
尝试使用类基础视图。
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class Follow(View):
def post(self, request):
user = request.POST.get('user')
follower = request.POST.get('follow')
action = request.POST.get('action')
target = User.objects.get(username=user)
sourceusr = User.objects.get(username=follower)
if action == 'follow':
target.followers.append(sourceusr)
sourceusr.following.append(target)
return JsonResponse({'Following': target.following}, safe=False,
status=201)
或者
class Follow(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(Follow, self).dispatch(request, *args, **kwargs)
def post(self, request):
user = request.POST.get('user')
follower = request.POST.get('follow')
action = request.POST.get('action')
target = User.objects.get(username=user)
sourceusr = User.objects.get(username=follower)
if action == 'follow':
target.followers.append(sourceusr)
sourceusr.following.append(target)
return JsonResponse({'Following': target.following}, safe=False,
status=201)
网址.py:
path('follow/', Follow.as_view(), name='follow'),
推荐阅读
- python - Django 找不到模块
- azure - 我可以将脚本添加到 SignUP 和 SignIn 组合吗?
- webpack - 带有模板的 HtmlWebpackPlugin 在最后添加了一个不需要的
- c - printf 3d指针数组中的内容时堆缓冲区溢出
- debugging - 从命令行启动时出现错误后如何出现颜色错误并启动到 ipython 调试器?
- javascript - ReactNative:等待/异步函数在继续之前等待结果
- java - 如何从 Pentaho 连接到 MSSQL?
- javascript - ASP 按钮 OnClick 未在 javascript 弹出窗口中触发
- vue.js - Vue 路由 - 如何将干净的 URL 与 /:slug 一起用于多个组件
- python - 如何检测鼠标是否悬停在按钮上?PyGame 按钮类在悬停时不显示文本或更改颜色