Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django automatic login after user registration (1.4)

I have an issue where I am successfully registering users - however, I want users to be logged in on registration. Here is the code that represents my registration view. Any thoughts on why the user is not auto-logged in?

Notes:

  • The user is being registered correctly, they can log in after this
  • authenticate(**kwargs) is returning the correct user
  • In settings.py I have:

    AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) 
    

Thanks!

def register(request):
    user_creation_form = UserCreationForm(request.POST or None)
    if request.method == 'POST' and user_creation_form.is_valid():
        u_name = user_creation_form.cleaned_data.get('username')
        u_pass = user_creation_form.cleaned_data.get('password2')
        user_creation_form.save()
        print u_name # Prints correct username
        print u_pass # Prints correct password
        user = authenticate(username=u_name,
                            password=u_pass)
        print 'User: ', user # Prints correct user
        login(request, user) # Seems to do nothing
        return HttpResponseRedirect('/book/') # User is not logged in on this page
    c = RequestContext(request, {'form': user_creation_form})
    return render_to_response('register.html', c)
like image 415
zallarak Avatar asked Mar 04 '13 00:03

zallarak


Video Answer


2 Answers

Ah! I figured it out. In case anyone has this issue, import login from django.contrib.auth if you are calling it manually - I was importing the view. Commented out code represents the bad import for my situation.

# from django.contrib.auth.views import login
from django.contrib.auth import authenticate, logout, login
like image 156
zallarak Avatar answered Oct 30 '22 19:10

zallarak


I do it this way:

u.backend = "django.contrib.auth.backends.ModelBackend"
login(request, u)
like image 35
Adam Silver Avatar answered Oct 30 '22 19:10

Adam Silver