tags:

views:

65

answers:

1

This is what I am currently using for registration:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            messages.info(request, "Thanks for registering. Please login to continue.")
            return HttpResponseRedirect("/dashboard/")
    else:
        form = UserCreationForm()
    return render_to_response("accounts/register.html", {
        'form': form,
    }, context_instance=RequestContext(request))

Is it possible not to require the user to login manually after creating an account, but rather simply to log them in automatically? Thanks.

edit: I had tried the login() function without success. I believe the problem is that AUTHENTICATION_BACKENDS was not set.

+3  A: 

Using the authenticate() and login() functions:

from django.contrib.auth import authenticate, login

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            messages.info(request, "Thanks for registering. You are now logged in.")
            new_user = authenticate(username=request.POST['username'],
                                    password=request.POST['password'])
            login(request, new_user)
            return HttpResponseRedirect("/dashboard/")
Ben James
Thank you. I had tried this without success, but now I realize the problem was that I had not specified the backend. The lines: new_user.backend='django.contrib.auth.backends.ModelBackend' login(request, new_user)do the trick. (Or should the backend be specified elsewhere rather than every time there is a registration?)
Chris
Set `AUTHENTICATION_BACKENDS` to `django.contrib.auth.backends.ModelBackend` in `settings.py`. For further info, see http://docs.djangoproject.com/en/1.2/topics/auth/#specifying-authentication-backends.
David Antaramian
Even with that set, I get the error "'User' object has no attribute 'backend'"
Chris
Ah, you have to call `authenticate()` first otherwise there is no `backend` set. I've updated my answer to show this.
Ben James
Thanks, that works perfectly. I think setting 'new_user = ' twice is (part of) what tripped me up.
Chris