Django评论CSRF错误

时间:2015-12-15 08:59:50

标签: django django-rest-framework csrf django-comments django-rest-auth

获取csrf错误我无法弄清楚如何修复,我有休息auth工作,用户可以更新他们的详细信息,如下所示: enter image description here

但是Django Comments我使用相同的csrf令牌得到此csrf错误错误:

enter image description here

我想在/ comments / post / endpoint上摆脱这个错误,这样这个端点的行为类似于/ rest-auth / user / view,它接受"授权:令牌792b5fb27b4fe805e895c91274f26b6ab13cb654"相关的标题字段向经过身份验证的用户提供数据。

以下是csrf相关的decotaros对屏幕截图中显示的各个视图的影响: 来自/ comments / post / endpoint

@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

来自/ rest-auth / user / endpoint

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def get_user(request, **kwargs):
    pk = request.data['pk']

    user = MyUser.objects.get(pk=pk)
    serializers = UsersSerializer(user)
    return Response(serializers.data)

3 个答案:

答案 0 :(得分:2)

您使用的内容类型错误。请将其更改为application/json,然后重试。

答案 1 :(得分:1)

我认为您正在使用django-rest-framework,默认情况下会附带csfr令牌,但邮递员会发送一个csfr令牌,这就是您收到该错误的原因。

清理cookie可能会解决问题。

答案 2 :(得分:1)

端点的装饰器不同,因此您需要相应地调整标头。 对于您的/ rest-auth / view,需要WWW-Authenticate标头为mentioned here

注释视图/ comments / endpoint包含csrf_protect装饰器,这意味着标头必须与cookie中返回的csrf-token匹配,因为Fede在您的标头中提到您只需要'X-CSRFToken',其中包含来自曲奇饼。