auto login with registration

Date: March 23rd 2016
Last updated: March 23rd 2016

I have created a registration form (see register users) and a login page (see login user). However, when a person uses the registration form the user is redirected to another page but is not logged in automatically. This example provides the code to link registration with login. I found the original answer at: http://stackoverflow.com/questions/3222549/how-to-automatically-login-a-user-after-registration-in-django.

Reminder: I am using a method from forms.py called MyRegistrationForm() which includes a save() method. username and password1 are included fields of model User which are defined in MyRegistrationForm().

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)   
        if form.is_valid():
            form.save()

            ######################### SOLUTION ###########################
            new_user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'],)
            login(request, new_user)
            return HttpResponseRedirect('/')
            ##############################################################

    args = {}
    args.update(csrf(request))
    args['form'] = MyRegistrationForm()

    return render(request, 'surferprofile/register.html', args)

results matching ""

    No results matching ""