简体   繁体   中英

Django automatic login after signup

I'm trying to get users automatically logged in after registration. However the user only seems to be logged in for the duration of rendering the next html page ( user.is_authenticated returns True in my templates) and gets logged out immediatly after ( request.user returns AnonymousUser in a method I call via AJAX on the next page - moving to another page also makes clear you are not logged in anymore since my templates render the login instead of the logout links again). If I try the commented code instead authenticate() always returns NONE.

What am I doing wrong?

def signup_view(request):
    if request.method == 'POST':
        form = UserSignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            send_confirmation_email(user, current_site.domain)
            # user_login = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
            # login(request, user_login)
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            args = {'user': user}
            return render(request, 'accounts/signup_success.html', args)
    else:
        form = UserSignUpForm()
    args = {'form': form, 'project_name': settings.PROJECT_NAME}
    return render(request, 'accounts/signup.html', args)

Please use following lines of code. It may full fill your requirements.

def signup(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=raw_password)
        login(request, user)
        return redirect('records:dashboard')
else:
    form = UserCreationForm()
return render(request, 'registration/signup.html', {'form': form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM