Menu
CoddyTech

Who Is Visiting

Part of the Users and Accounts section of Coddy's Django journey. Lesson 1 of 16.

Anyone who opens this notes app sees every note. To give each person their own notes, the site first has to know who is visiting.

Django's app django.contrib.auth stores accounts in its User model: a username, a hashed password, an email. When someone logs in, Django remembers them with a session. The browser sends back a small value, a cookie, with every request, and it points to a row on the server.

On every request Django puts the visitor on request.user, and templates get it as user. A visitor who has not logged in is an AnonymousUser, so ask with is_authenticated. A shop shows a banner only to visitors:

{% if not user.is_authenticated %}
    <p class="banner">Make an account to save your cart.</p>
{% endif %}
challenge icon

Challenge

Easy

In base.html, inside <div class="account">, show who is visiting. When someone is signed in, the box shows Signed in as and their username, like Signed in as ada. Otherwise it shows You are not signed in.

Open /: it says You are not signed in. Log in at /admin/ as ada (password coddy-pass-123), then open /: Signed in as ada.

Try it yourself

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{% block title %}Notes{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'notes/style.css' %}">
</head>
<body>
    <header>
        <a class="brand" href="{% url 'notes:list' %}">Notes</a>
        <nav>
            <a href="{% url 'notes:create' %}">New note</a>
        </nav>
        <div class="account">
        </div>
    </header>
    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

All lessons in Users and Accounts

Practice on your own: Django playground