如何修复django python中的CSRF错误?

时间:2014-11-10 06:06:19

标签: python django

我在登录表单中输入提交按钮时收到此错误 禁止(403)CSRF验证失败。请求中止。 失败的原因:CSRF令牌丢失或不正确。


的login.html

<form method="post" action="/index/">{% csrf_token %}
    <table border="0">
        <tr><th><label for="id_username">Username:</label></th><td></td></tr>
        <tr><th><label for="id_password">Password:</label></th><td></td></tr>
    </table>
    <input type="submit" value="Login" />
    <input type="hidden" name="next" value="/home" />
</form>

views.py

def user_login(request):
    # Like before, obtain the context for the user's request.
    context = RequestContext(request)

    # If the request is a HTTP POST, try to pull out the relevant information.
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        username = request.POST['username']
        password = request.POST['password']

        # Use Django's machinery to attempt to see if the username/password
        # combination is valid - a User object is returned if it is.
        user = authenticate(username=username, password=password)

        # If we have a User object, the details are correct.
        # If None (Python's way of representing the absence of a value), no user
        # with matching credentials was found.
        if user:
            # Is the account active? It could have been disabled.
            if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                login(request, user)
                return HttpResponseRedirect('/login/')
            else:
                # An inactive account was used - no logging in!
                return HttpResponse("Your Rango account is disabled.")
        else:
            # Bad login details were provided. So we can't log the user in.
            print "Invalid login details: {0}, {1}".format(username, password)
            return HttpResponse("Invalid login details supplied.")

    # The request is not a HTTP POST, so display the login form.
    # This scenario would most likely be a HTTP GET.
    else:
        # No context variables to pass to the template system, hence the
        # blank dictionary object...

        return render_to_response('login/login.html', {}, RequestContext(request))

2 个答案:

答案 0 :(得分:1)

当您从Django中的HTML表单发布数据并启用CSRF时,您需要在表单中包含token

{% csrf_token %}

Reference docs

答案 1 :(得分:0)

在表单

中添加csrf标记
<form id="login_form">{% csrf_token %}</form>