[Django]-Redirect to admin for login

7👍

You’re missing an initial / in the URL: /admin/?next=...

However this still won’t work, as the admin URL doesn’t know anything about the next parameter. That’s only for the actual login views. With your code, the user will be logged into the admin but will not be redirected back to your page.

You should build a login template and wire it up to the built-in login views. Then instead of checking is_authenticated in the view, you should just use the login_required decorator.

@login_required
def main(request):
   ...

3👍

Your request.path shouldn’t be /main/. Try it without the first.

1👍

  1. urls.py:

                         url('^', include('django.contrib.auth.urls')),
    
  2. registration/login.html:

  <h3>Login foo</h3>
    <form method="post" action="">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Login">
    </form>
  1. views.py

    def only_for_users(request):
       if not request.user.is_authenticated():
           return HttpResponseRedirect('/login/?next=%s' % request.path)
    
       // fetch some really interesting data
    
       env=(django.get_version(),settings.BASE_DIR,sys.version)
       envMod=collections.OrderedDict(sorted(sys.modules.items()))
       return render(request,'env.html',{'env':env, 'envMod':envMod})
    

It works for Django 1.6 and uses the built-in login (look at the urls.py) and template. So you do not need to build a view function.

Info on urls

👤Timo

1👍

If you want to redirect to admin for login for specific view, and then to redirect back to the view url after successful login you only need to do two things:

  1. Add LOGIN_URL to settings.py inside your django project module:
...
LOGIN_URL = '/admin/login/'
  1. Add @login_required as decorator to your view function inside views.py:
from django.contrib.auth.decorators import login_required
...
@login_required
def main(request):

Once you set LOGIN_URL = '/admin/login/' you can use @login_required on whatever view in entire django project and it will redirect to admin for login and after successful login will redirect back to the view url.

Also now you don’t need to use is_authenticated any more inside of a view as Daniel Roseman already said.

The good thing is that now you also don’t need to build a login template and wire it up to the built-in login views.

What is also good with this approach is the you have flexibility to easily add or remove this kind of authentication to whatever view you want.

Leave a comment