1
votes

I am trying to get a user register in Django and then redirects him to his home page ie 'dashboard'. Though, it gets register but due to the authentication provided(@login_required), the user is not redirected to his home page. The user again has to submit his username and password to get login into the page.

Here is my views.py

def register(request):
    form = RegisterForm(request.POST or None)

    if(form.is_valid()):
        user = form.save()
        login(request,user)
        return redirect('/dashboard/')

    ctx = {
            'form' : form
    }

    return render_to_response('home/register.html',ctx, context_instance = RequestContext(request))


@login_required
def dashboard(request):
    HttpResponse("HELLO")
1

1 Answers

2
votes

You need to use authenticate() first, before calling login().

from django.contrib.auth import authenticate, login
if(form.is_valid()):
    form.save()
    new_user = authenticate(username=form.cleaned_data.get('username'), 
                            password= form.cleaned_data.get('password'))
    login(request,new_user)
    return redirect('/dashboard/')

From Django docs:

When you’re manually logging a user in, you must call authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.