Django Bootstrap 模式表单缺少 csrf 令牌

问题描述 投票:0回答:1

我正在使用 django 引导模式表单进行登录和注册弹出窗口,但它们缺少 csrf 令牌,我收到“来自 POST 的 CSRF 令牌不正确”。注册或登录时出错。

我的 html 模板中有

{% csrf token %}
,所以这不是问题。我已经通过视图重新配置(添加方法装饰器和表单来渲染上下文)看到了这个问题的很多答案,但由于我使用的是引导模式表单文档示例中基于类的视图,所以我无法重复这样的解决方案。我的观点是这样的:

class CustomLoginView(BSModalLoginView):
        authentication_form = CustomAuthenticationForm
        template_name = 'login.html'
        success_message = 'Success: You were successfully logged in.'
        extra_context = dict(success_url=reverse_lazy('home'))

class SignUpView(BSModalCreateView):
        form_class = CustomUserCreationForm
        template_name = 'signup.html'
        success_message = 'Success: Sign up succeeded. You can now Log in.'
        success_url = reverse_lazy('home')

我尝试用这样的方法重写它们:

class SignUpView(BSModalCreateView):

        def signup_view(request):
            form = CustomUserCreationForm()
            if request.method == "GET":
                return render(request, 'signup.html', context={'form':form})
            if request.method == "POST":
                data = request.POST
                if form.is_valid():
                    user = form.save(False)
                    user.set_password(user.password)
                    user.save()

                    return redirect('home')

但随后表格就停止工作了。另外,我尝试从 django-braces 添加 CsrfExemptMixin,但这也不起作用。唯一有效的解决方案是完全禁用 csrf 检查,但我真的想保留它们,因为它更安全。我错过了什么吗?如何更改这些基于类的视图以便 csrf 令牌开始工作?

django django-views django-forms bootstrap-modal csrf-token
1个回答
0
投票

关闭CSRF就没有保护了

© www.soinside.com 2019 - 2024. All rights reserved.