DEV Community

Cover image for Login Page using UserCreationForm (Django) – Part 4
balt1794
balt1794

Posted on

Login Page using UserCreationForm (Django) – Part 4

The register page is done, so now users can sign up, however, we need a way for users to log in. The focus of this post will be the login page.

Back in part 1, we created a template for the login page which only has a heading tag at the moment.

Open login.html and add the following code.

Login.html


<!-- path -> users/templates/users/login.html -->

<div class="login-page">
  <div class="form">
    <form method="POST" action="">
      {% csrf_token %}
      <h3 class="login-title">LOGIN</h3>
      <div class="input-group mb-3">
        <input type="text" name="username" placeholder="Username..." class="form-control">
      </div>
      <div class="input-group mb-2">
          <input type="password" name="password" placeholder="Password..." class="form-control" >
      </div>
      <button type="submit"> Submit </button>
      <p class="message">Don't have an account? <a href="{% url 'users:register' %}">Register</a></p>
    </form>
  </div>
</div>


<!-- baltlogs.com -->

Enter fullscreen mode Exit fullscreen mode

— Created a login form so that users can sign in.

— Created a link at the bottom of the form which takes users to the register page, in case, they need to register first.

Save changes and run server to see the login form.

Screen Shot 2021-05-20 at 3.24.13 PM

Before taking care of the code for the login form, we need to create a homepage for users to land there after logging in.

Follow the same process as in the first post of the series to create a homepage.

If you know how to do this, you can skip this part.

If you are having trouble creating the homepage, follow the steps below.

— Create a homepage template inside the templates/users folder.

Homepage.html


<!-- path -> users/templates/users/homepage.html -->

<h1>Welcome to the Homepage</h1>

<!-- baltlogs.com -->

Enter fullscreen mode Exit fullscreen mode

— Include the path to the homepage in urls.py.

Urls.py


#path -> users/urls.py

from django.urls import path
from .import views

app_name = 'users'

urlpatterns = [

    path('login/', views.login_page, name='login'),
    path('register/', views.register_page, name='register'),
    path('home/', views.home_page, name='home'),
]

#baltlogs.com

Enter fullscreen mode Exit fullscreen mode

— Create the homepage view in views.py.

Views.py


#path -> users/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from .forms import CustomUserForm

def login_page(request):
    return render(request, 'users/login.html')


def home_page(request):
    return render(request, 'users/home.html')

def register_page(request):
    if request.method != 'POST':
        form = CustomUserForm()
    else:
        form = CustomUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('users:login')

    context = {'form': form}

    return render(request, 'users/register.html', context)

#batlogs.com

Enter fullscreen mode Exit fullscreen mode

Let’s take care of adding the necessary logic to make the form work.

Views.py


#path -> users/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from .forms import CustomUserForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages


def login_page(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('users:home')
        else:
            messages.info(request, 'Try again! username or password is incorrect')

    context = {}
    return render(request, 'users/login.html', context)


def logout_page(request):
    logout(request)
    return redirect('users:login')


def home_page(request):
    return render(request, 'users/home.html')


def register_page(request):
    if request.method != 'POST':
        form = CustomUserForm()
    else:
        form = CustomUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('users:login')

    context = {'form': form}
    return render(request, 'users/register.html', context)

#batlogs.com

Enter fullscreen mode Exit fullscreen mode

There’s a lot to unpack here, so try to read and follow carefully.

Imports:

— Imported authenticate, login, and logout from the Django authentication system.

authenticate -> verifies a set of credentials; username and password for the default case.

login -> logs in users

logout -> logs out users

— Imported messages which allows to display one-time messages after processing forms.

Login_page view:

— The request will be a POST because users will be submitting the form.

— Once users submit the form, we use the username and password from the form for authentication. Django compares the credentials from the form with the information in the database to make sure there is a user with those credentials.

— If the user is authenticated successfully, we will login him in and redirect him to the homepage.

— If the user is not authenticated, we will display the message: ‘Try again! username or password is incorrect’.

Logout_page view:

— Use logout to log out users.

Open homepage.html to add a couple of links including the logout link.

Homepage.html


<!-- path -> users/templates/users/homepage.html -->

<h1>Welcome to the Homepage</h1>

{% if user.is_authenticated %} 

<a class="logout-link" href="{% url 'users:logout' %}">Logout</a>

{% else %}
<a class="register-link mr-4" href="{% url 'users:register' %}">Register - </a> 
<a class="login-link" href="{% url 'users:login' %}">Login</a> 

{% endif %}

<!-- baltlogs.com -->

Enter fullscreen mode Exit fullscreen mode

— Added an if statement that works as follows:

If the user is authenticated, then show the logout link.

If the user is not authenticated, then show the register and login link.

Before you start logging in users, open login.html and add the following lines of code at the bottom of the form to display the flash message.

Login.html


<!-- path -> users/templates/users/login.html -->

<div class="login-page">
  <div class="form">
    <form method="POST" action="">
      {% csrf_token %}
      <h3 class="login-title">LOGIN</h3>
      <div class="input-group mb-3">
        <input type="text" name="username" placeholder="Username..." class="form-control">
      </div>
      <div class="input-group mb-2">
          <input type="password" name="password" placeholder="Password..." class="form-control" >
      </div>
      <button type="submit"> Submit </button>
      <p class="message">Don't have an account? <a href="{% url 'users:register' %}">Register</a></p>
    </form>
  </div>
{% for message in messages %}
    <p class= "text-center">{{message}}</p>
  {% endfor %}
</div>


<!-- baltlogs.com -->

Enter fullscreen mode Exit fullscreen mode

Save changes and run the server.

If you already created an account, once you log in with your credentials you should be taken to the homepage.

If you do not have an account and try to log in, you should see the same login page, but with the flash message displayed at the bottom of the form.

Screen Shot 2021-05-21 at 6.43.35 PM

Don’t forget to check that the homepage links work.

In the next post, we will style the login form.

Part 5 –> Soon

Twitter

Registration Page using UserCreationForm (Django) – Part 1

Registration Page using UserCreationForm (Django) – Part 2

Registration Page using UserCreationForm (Django) – Part 3

Django 3..2..1..Takeoff Book

Personal Website

Top comments (0)