Logging in - 30 days of Django

Logging in - 30 days of Django

/ #Django


In this part, we will learn more concepts of the Django authentication system.

First, let's begin with making it possible to log in. Django has a built in view for this, so the only thing we need to handle is the url and the templates.

Open up userprofile/urls.py and make the following changes:

from django.contrib.auth import views as auth_views # 1. New
from django.urls import path

from . import views

urlpatterns = [
    path('sign-up/', views.signup, name='signup'),
    path('log-in/', auth_views.LoginView.as_view(template_name='userprofile/login.html'), name='login'), # 2. Change
]

1. First, we import all of the authentication views from Django. And we import them "as auth_views", so the names doesn't crash with ours.
2. Then, we append the path to the urlpatterns. This is a Class Based View, and the only thing we need to specify is where the template is located. Django will handle all of the magic for us.

Create a new file called "login.html", and copy the contents from signup.html.

{% extends 'task/base.html' %}

{% block content %}
    <div class="edit-tasks">
        <h1>Log in</h1>

        <form method="post" action=".">
            {% csrf_token %}

            {{ form.as_p }}

            <button>Log in</button>
        </form>
    </div>
{% endblock %}

You can just rename the title and button.

We didn't see in the url file that there was supposed to be a variable called "form", but this is the default way for Django to handle this. So now you can try this out by going to "/log-in/" in your browser.

Last step of this part is to make some changes in the base.html file:

...

<nav class="navbar is-dark">
    <div class="navbar-brand">
        <a href="/" class="navbar-item is-size-4">Toodoo</a>
    </div>

    <div class="navbar-menu">
        <div class="navbar-end">
            {% if request.user.is_authenticated %}
                <a class="navbar-item">Log out</a>
            {% else %}
                <a href="{% url 'signup' %}" class="navbar-item">Sign up</a>
                <a href="{% url 'login' %}class="navbar-item">Log in</a>
            {% endif %}
        </div>
    </div>
</nav>

...

So here we add a new menu inside the navigation bar. We use the if-tag from Django to check if the user is authenticated. If the user is not authenticated, we show the sign up and login links. But if the user is authenticated, we show a log out link (Will be implemented in the next part).

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.