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):
...
- [Django]-Django: How to dynamic filter foreignkey choices by Customizing the Django_Admin
- [Django]-Can we pass array/list to template content blocks in django? python
- [Django]-Composite primary key, Google app engine (django)
- [Django]-Access Django App on AWS ec2 host
- [Django]-Can I have 2 Django sites using 2 different version of Python on 1 domain?
1👍
-
urls.py:
url('^', include('django.contrib.auth.urls')),
-
registration/login.html:
<h3>Login foo</h3>
<form method="post" action="">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
-
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
- [Django]-Django ORM: Joining QuerySets
- [Django]-Django Rest Framework: PUT/POST fails in case of blank optional fields in nested serializer
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:
- Add
LOGIN_URL
tosettings.py
inside yourdjango project module
:
...
LOGIN_URL = '/admin/login/'
- Add
@login_required
as decorator to your view function insideviews.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 whateverview
in entire django project and itwill redirect to admin for login
andafter 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.