2

Using the django.contrib.auth.views.login method to perform the sign in method in my project, how to prevent the access to the /registration/login/ page again after successful login?

Josh Scholl
  • 143
  • 15
blindOSX
  • 711
  • 8
  • 14

3 Answers3

5

You could deocrate your login-view with this AnonymousRequired-Decorator.

See this blog post for some background information on decorators which even explains things using your specific problem : http://passingcuriosity.com/2009/writing-view-decorators-for-django/

arie
  • 18,737
  • 5
  • 70
  • 76
  • I think if a user is logged in, it's normal to deny him the access again to the login form. Doesn't it? – blindOSX Apr 13 '11 at 15:27
  • About your approach, the problem is that I am using the django.contrib.auth.views.login method so I shouldn't modify it. – blindOSX Apr 13 '11 at 15:28
  • Using the decorator isn't modifying the view. You can apply the decorator in your urlpatterns. – Mark Lavin Apr 13 '11 at 16:27
  • 2
    Using a decorator in your urls.py is explained in this answer: http://stackoverflow.com/questions/2140550/how-to-require-login-for-django-generic-views/2140678#2140678. On the other hand it isn't too hard to write a custom login view and decorate it (or intercept calls from already logged in users), as Thierry suggests. – arie Apr 13 '11 at 17:35
2

In your login view, check if a user is already authenticated:

def your_login(request):
    if request.user.is_authenticated():
        return redirect('yourhomepage') # or somewhere else or last url

EDIT

Assuming you want to keep authenticating that way, the only way I can think of redirecting is through a middleware.

  1. Create a middleware
  2. Check if the current url matches your login url
  3. If user is already authenticated, redirect to home page, otherwise process as usual
Thierry Lam
  • 45,304
  • 42
  • 117
  • 144
  • Hi, it's correct but as I mentioned below I dont have my custom login view because I am using the django.contrib.auth.views.login and I can't modify it – blindOSX Apr 13 '11 at 15:46
  • Can you show the code where your are using the django login function? – Thierry Lam Apr 13 '11 at 15:52
  • Of course, is a simple mapping in my URLConf: (r'^login/$', 'django.contrib.auth.views.login') – blindOSX Apr 13 '11 at 16:00
0

For check In your login view, check if a user is already authenticated or no you should take it:

def your_login(request):
if request.user.is_authenticated():
    return redirect('/') #redirect to your home page

It is correct

Thanks for confirming my answer