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: a cookie, a small value the browser sends back with every request, that 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
EasyIn base.html, inside <div class="account">:
- A signed in user reads
Signed in asand their username, likeSigned in as ada. - Everyone else reads
You are not signed in.
Press Run and open /. Then log in at /admin/ as ada (password coddy-pass-123) and open / again.
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