Django中的CSRF错误; 如何将CSRF添加到登录视图?

zal*_*rak 1 python django csrf django-csrf

我有一个简单的表单,我希望用户能够登录; 这里是带有CSRF标签的模板代码:

<html>
<head><title>My Site</title></head>

<body>
    <form action="" method="post">{% csrf_token %}
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">

        <input type="submit" value="login" />
        <input type="hidden" name="next" value="{{ next|escape }}" />
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在这是我的views.py页面.问题是我在哪里放入CSRF支持部分(现在我得到CFRS令牌错误),我该怎么做?

from django.contrib import auth

def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page
        return HttpResponseRedirect("/account/loggedin/")
    else:
        # Show an error page
        return HttpResponseRedirect("account/invalid/")

def logout_view(request):
Run Code Online (Sandbox Code Playgroud)

小智 5

您必须将RequestContext视图添加到呈现页面的视图{% csrf_token %}中.以下是教程中的示例:

# The {% csrf_token %} tag requires information from the request object, which is 
# not normally accessible from within the template context. To fix this, 
# a small adjustment needs to be made to the detail view, so that it looks 
# like the following:
#
from django.template import RequestContext
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p},
                           context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

context_instance=RequestContext(request)部分是重要的部分.这使得RequestContext在呈现时可用于表单模板.