Django-Registration: How to prevent logged in user

2019-09-07 15:36发布

问题:

I've just started to use django-registration. I have two questions:

  1. How do you prevent a logged in user from going to the register page?

  2. How do you automatically sign in a user after activation?

I prefer not changing any code in the app itself.

For question 2, I've already read the docs where it says to write "a function which listens for the appropriate signal; your function should set the backend attribute of the user to the correct authentication backend, and then call django.contrib.auth.login() to log the user in." I don't know django well enough to understand what this means or how to implement this. Could you guys help/point me in the right direction?

Edit:

Tried doing some signals, does not yet work, not sure what's wrong:

def loginActivationCallback(sender, user, request, **kwargs):
    print user
    print "registered"

user_registered.connect(loginActivationCallback)

Also because I'm using Django 1.5, I didn't do pip install django-registration(does not fully support 1.5), but instead copied the registration folder into my project. Not sure if this affects the signals.

回答1:

Simply what you can do is check in your register view

 if request.user.is_authenticated:
     #redirect user to the profile page 
     return HttpResponseRedirect('/profile/')


回答2:

from registration.signals import user_activated

def login_user(sender, user, request, **kwargs):
    user.backend='django.contrib.auth.backends.ModelBackend' 
    login(request,user)
user_activated.connect(login_user)