django Rest 框架工作:令牌认证

时间:2021-05-13 12:03:29

标签: python django post django-rest-framework http-token-authentication

我有一张桌子('喜欢')喜欢帖子

class Likes(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

我有一个餐桌课程:

class Courses(models.Model):
    title = models.CharField(max_length=100, null=True)
    description = RichTextUploadingField(null=True)
    like = GenericRelation(Likes)

我使用 restman opera 扩展向我的 api 发送 POST 请求 如果我使用浏览器登录,我会收到错误

 "detail": "CSRF Failed: CSRF token missing or incorrect."

但我只使用restman(我不使用浏览器登录)一切正常

设置.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',  
        'rest_framework.authentication.SessionAuthentication', 
        'rest_framework.authentication.TokenAuthentication'
    ]
}

查看:

@api_view(['POST'])  
@login_required   
def f_like(request):
    r = {'data': None}
    id_o = request.POST.get('id')
    type_o = request.POST.get('type')
    if(type_o in {'Courses', 'Course_Sessions', 'Course_Session_Exercise'} and id_o.isdigit()):
        model = eval(type_o)
        if(obj := model.objects.filter(id=id_o)):
            obj = obj[0]
            a = ['title', obj.title]
            if(c2 := obj.like.filter(user=request.user)):
                c = c2[0]
                c.delete()
                a.append(0)
            else:
                obj.like.create(user=request.user)
                a.append(1)
            r['data'] = a
    return Response(r)

1 个答案:

答案 0 :(得分:0)

在 MIDDLEWARE 的 setting.py 中尝试删除/注释此行:

'django.middleware.csrf.CsrfViewMiddleware'

这将禁用 CSRF 验证。