简体   繁体   中英

Django can't identify the user after registering an account *AnonymousUser*

So the goal is for a new user to register an account and then get redirected to the home page and recognized . So that the user does not have to register for their account then go through the process of logging in right after. I want a standard registration, like Instagram, Twitter, and other professional applications.

So far, I'm where the user can register and redirect them to the homepage, but when I try to print their name on the screen, I get AnonymousUser. The user's information is written to the database after registering, but Django doesn't know who the user is. For Django to know who is logged in after registering, they have to log out and then log in right after registering their account. If anyone could help, I would be much appreciated it.

Views.py

from django.shortcuts import render, redirect
from .forms import RegisterForm
from django.contrib import messages

def register(response):
    if response.method == "POST":
        form = RegisterForm(response.POST)
        if form.is_valid():
            form.save()
            return redirect("/")
    else:
        form = RegisterForm()


    return render(response, "register/register.html", {"form": form})

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=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'],
                                    )
            login(request, new_user)
            return HttpResponseRedirect("/dashboard/")

originally answered

after successful registration POST REQUEST explicitly log in the users using the login method and you can access the name of the user without having the user to login again...

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