首页 > 解决方案 > 为什么 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)

标签: djangodjango-rest-framework

解决方案


尝试使用类基础视图。

 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'),

推荐阅读