我有一个表('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(我不使用浏览器登录(所有东西都可以
设置.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)
在MIDDLEWARE中的setting.py
中,尝试删除/注释此行:
'django.middleware.csrf.CsrfViewMiddleware'
这将禁用CSRF验证。