How to redirect django.contrib.auth.views.login after login?


I added django.contrib.auth.views.login everywhere in my webpage, for that I had to load a templatetag (that returns the AuthenticationForm) in my base.html. This templatetags includes the registration/login.html template.

The login is working ok but I want it to redirect the users to the same page they are before login. Now, it redirects me to /wherever_i_am/login wich shows registration/login.html with the 'login ok' or 'login fails' messages but without the rest of base.html.

I have followed django documentation and a few SO questions like this but I cannot redirect correctly. I have modified the next variable but it doesn't seem to work (next={{ request.get_full_path }} redirects me to /wherever_i_am/login ...again)

Have you tried something similar? any ideas?

UPDATE1 Now, the question could be something like: Do I have to declare my own login view if I want to include the login form everywhere in my web page?

Thank you.

7/23/2019 2:09:16 PM

Accepted Answer

Found answer:

Change settings.LOGIN_REDIRECT_URL in your,

below code is copy from django:

   if request.method == "POST":
    form = authentication_form(data=request.POST)
    if form.is_valid():
        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = settings.LOGIN_REDIRECT_URL
9/26/2013 9:37:26 PM

The below allows redirects the user to the page they were attempting to access after they log in, but without having to write a custom view. It contains all the code you need to add to make it work. (As an aside, not all the TEMPLATE_CONTEXT_PROCESSORS are needed, but if you set a value to it explicitly you overwrite the defaults so need to re-add them.)


from django.contrib.auth.views import login, logout
...the other imports for your app ...

urlpatterns = patterns('',
    (r'^login/$', login, {'template_name':'login.html'} ),
    (r'^logout/$', logout,{'template_name':'logout.html'}),
    ...the other urls for your app...


    <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
        {% csrf_token %}
       <input type="submit" value="login" />
       <input type="hidden" name="next" value="{{ next }}" />


<p>You are logged out. To log in again, click <a href="/login/">here</a>.</p> 

def view1(request):
    ....this is a view you want to protect with security...

def view1(request):
    ....this is a view you want to protect with security...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow