Tech With Tim Logo
Go back

Login/Logout Page

Logging In

Now that we have created a sign up page we need to create a way for users to log in and log out of their account. The first part of this tutorial will show you how to create a log in page, the next will show logout.

Django comes with a few build in applications that automatically generate specific user authentication forms like a log in form. To use these we need to add the following to our file from within the mysite directory.

from django.contrib import admin
from django.urls import path, include
from register import views as v

urlpatterns = [
    path("register/", v.register, name="register"),
    path('', include("main.urls")),
    path('', include("django.contrib.auth.urls")), # <-- added

Now we have a valid path to a /login and /logout page.

The next step is to create the views for each of these pages. We will start by creating a folder inside of our register apps template folder called "registration". IT IS VERY IMPORTANT THAT YOU NAME IT EXACTLY THAT. It can be placed inside any applications templates folder but it must be in one.

Inside this folder we will create a file called: "login.html". Again this must be the name.

Now we can code the login.html file to display whatever we'd like:

# login.html
{% extends "main/base.html" %}

{% block title %}
Login Here
{% endblock %}

{% load crispy_forms_tags %}

{% block content %}
     <form method="post" class="from-group">
	{% csrf_token %}
	<p>Don't have an accoount? Create one <a href="/register">here</a></p>
	<button type="submit" class="btn btn-success">Login</button>	
{% endblock %}

And now we have a working login page! kuva_2023-04-25_151319838.png

Login/Logout Redirect

As of know visiting /login and /logout work but after submitting the form we are not redirected to another page. To change where you go after logging in or logging out you can add the following to your file.


Simply define the url that you'd like to be redirected to as a string.

Design & Development by Ibezio Logo