Menu
CoddyTech

Logging In

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

The site can tell who is signed in, but it has no page to sign in on. Django has the view, LoginView. One line in the project's urls.py adds it, with the logout and password pages:

path("accounts/", include("django.contrib.auth.urls")),

Now /accounts/login/ exists, named login. The view renders registration/login.html with a form that has a username and a password field. That template is yours to write: an ordinary POST form. Django looks in the templates/ folder of every app. The path starts with registration/, not notes/, because Django's view does not know your app.

After a good login the view redirects to LOGIN_REDIRECT_URL. Its default, /accounts/profile/, does not exist here, so set it in settings.py.

challenge icon

Challenge

Easy

Add a login page.

  1. In mysite/urls.py, include django.contrib.auth.urls under accounts/.
  2. Create notes/templates/registration/login.html extending notes/base.html, that shows form in a POST form with {% csrf_token %} and a Log in button.
  3. In settings.py, set LOGIN_REDIRECT_URL to "/".
  4. In base.html, for signed out visitors, link Log in to {% url 'login' %}.

Log in as ada (password coddy-pass-123): the header says Signed in as ada.

Try it yourself

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("notes.urls")),
]

All lessons in Users and Accounts

Practice on your own: Django playground