【问题标题】:django Rest frame work : token authenticationdjango Rest 框架:令牌认证
【发布时间】:2021-08-03 17:13:43
【问题描述】:

我有一张表('like')来点赞帖子

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(我不使用浏览器登录)一切都很好

setting.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)

【问题讨论】:

  • 你的views.py中有@requires_csrf_token吗?
  • 不,我不知道。我添加我的观点
  • 您是否在应用中添加了 REST 框架?
  • 是的,我确实添加了“rest_framework”和“rest_framework.authtoken”setting.py 安装的应用程序

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


【解决方案1】:

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

'django.middleware.csrf.CsrfViewMiddleware'

这将禁用 CSRF 验证。

【讨论】:

  • 如果我这样做,会讨厌我网站的安全性吗?
猜你喜欢
  • 2013-01-28
  • 2023-03-29
  • 2016-08-12
  • 2015-08-24
  • 2014-12-24
  • 1970-01-01
  • 2015-03-25
  • 2023-03-16
  • 2019-04-11
相关资源
最近更新 更多