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
EasyAdd a login page.
- In
mysite/urls.py, includedjango.contrib.auth.urlsunderaccounts/. - Create
notes/templates/registration/login.htmlextendingnotes/base.html, that showsformin a POST form with{% csrf_token %}and aLog inbutton. - In
settings.py, setLOGIN_REDIRECT_URLto"/". - In
base.html, for signed out visitors, linkLog into{% 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