简体   繁体   中英

Django redirect after login

Im creating my first app in Django I decided I want logging window (smal one with username/password na "Log in" button) on EACH view. From base.html:

<div id="logging">
    {% if user.is_authenticated %}
    <h1>Witaj, {{user.username}}!</h1>
    {% else %}
     <form method="post" action="{% url 'harcowanie.views.login' %}">
    {% csrf_token %}
    <div  style="display: inline-block;">
    <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /></p>
    <p><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></p>
    </div>
    <div style="display: inline-block; position: relative; bottom: 25px;">
    <input class="decent_background" type="submit" value="Log in" />
    </div>
</form>
{% endif %}
    </div>

Any part of my views.py:

def login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request=request, user=user)
            return redirect(request.META['HTTP_REFERER'],   context_instance=RequestContext(request))
        else:
            pass
            # Return a 'disabled account' error message
    else:
        pass
        # Return an 'invalid login' error message.

    return redirect(request.META['HTTP_REFERER'],   context_instance=RequestContext(request))

But I'm getting error:

A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")

Looks like you use redirect in wrong way. Argument context_instance is not supported by this method. See docs .

About error. Ensure that view which rendered page from request.META['HTTP_REFERER'] uses RequestContext or manually import and use the processor to generate the CSRF token( docs ).

The error states that the CSRF token is not in your context. A good read to know what CSRF is about: here .

In order to generate the CSRF token, either enable the middleware in your settings, or generate by hand in your view, then pass it to your template. I strongly suggest to you to enable the middleware :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM