Home > Blockchain >  Why do we need to login user in signup_view an login_view function? Django
Why do we need to login user in signup_view an login_view function? Django

Time:09-29

So I need a theoretical answer here, not practical, I've been following this tutorial on Django anf everything seems quite understandable, but I'm not sure about one thing, so here are the views for signup page and login page:

def signup_view(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            #log the user in
            login(request, user)          


            return redirect("articles:list")
    
    else:
        form = UserCreationForm()

    return render(request, 'account/signup.html', {"form": form})

def login_view(request):
    if request.method == "POST":
        form = AuthenticationForm(data = request.POST)
        if form.is_valid():
            #log in the user
            user = form.get_user()
            login(request,  user)
            return redirect('articles:list')

    else:
        form = AuthenticationForm()
    return render(request, "account/login.html", {"form":form})


So my question is, why do I need to write login(request, user) twice, isn't the signup function saving the user in database and log in function simply logging it in?

CodePudding user response:

In the code, for post request and valid forms, the response is always a redirect to articles:list page.

If we assume the view articles:list as login required, users need to have an active session in order to view the page.

In the login_view function after authenticate is quite obvious that next step is to log the user in and redirect to articles:list

In the signup_view the logic might be, add user to database and redirect to articles:list, but since articles:list is login required, we need to log the user in.

Maybe that's the way they thought the logic for the example, it all depends on what you need since is not a rule to log the user in after register.

  • Related