Automatically logging in to Django after user registration (1.4)

I have a problem when I successfully register users - however, I want users to register when registering. Here is the code that represents my registration submission. Any thoughts on why the user is not auto-registered?

Notes:

  • The user registers correctly, he can log in after that
  • authenticate (** kwargs) returns the correct user
  • In settings.py, I have:

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

Thank!

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)
+5
source share
3 answers

! . - , django.contrib.auth, - . .

# from django.contrib.auth.views import login
from django.contrib.auth import authenticate, logout, login
+3

:

u.backend = "django.contrib.auth.backends.ModelBackend"
login(request, u)
+3

for view-based classes, here was the code that worked for me (django 1.7)

from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import FormView

class SignUp(FormView):
   template_name = 'signup.html'
   form_class = UserCreationForm
   success_url='/account'

   def form_valid(self, form):
      #save the new user first
      form.save()
      #get the username and password
      username = self.request.POST['username']
      password = self.request.POST['password1']
      #authenticate user then login
      user = authenticate(username=username, password=password)
      login(self.request, user)
      return super(SignUp, self).form_valid(form)
+1
source

All Articles