how i login to my new user account using login(request )

Viewed 18

in my base.html i wrote this code

{% if user.is_authenticated %}
      <div class="btn-group" >
  <button class="btn btn-primary" type="button" data-bs-toggle="dropdown" data-bs-auto-close="true" aria-expanded="false">
    welcome {{user.username}}
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">profile</a></li>
    <li><a class="dropdown-item" href="#">change password</a></li>
    <li><a class="dropdown-item" href="{% url 'logout'%} ">logout</a></li>
  </ul>
</div>
      {%else%}
      <a href="#" class ="btn btn-outline-secondary">login</a>
      <a href="{%url 'signup'%}" class ="btn btn-outline-primary">signup</a>
      {%endif%}

but everytime i create a new user it always shwos the ELSE condition html

this is my views:

'''

from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login
from .forms import SignUpForm


def signup(request):
    form = SignUpForm()
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            user =form.save()
            auth_login(request, user)
            return redirect('index')
    return render(request, 'signup.html', {'form': form})

'''

what is the problem

1 Answers

This is how I would typically write a Login view. This will only work after user has signed up and created the user and password.

from django.contrib.auth import authenticate, login, logout

def loginView(request):

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        auth = authenticate(request, username=username, password=password)
        if auth:
            login(request, auth)
            
            return redirect('profile')
        else:
            return redirect('index')

    return render(request, 'myapp/login.html')
``
Related