Understanding Django LoginView With Simple Example
In this tutorial, we'll learn how to use Django LoginView to create a custom login page.
example
views.py
In the views file, we need to import LoginView then create a simple CBV.
#loginView
from django.contrib.auth.views import LoginView
class AdminLogin(LoginView):
template_name = 'LoginView_form.html'
template_name: the template that will display the login form.
urls.py
in urls.py we need to a path for our CBV
#LoginView
path('login/', AdminLogin.as_view(), name="login")
settings.py
In settings.py, we need to add the following line.
LOGIN_REDIRECT_URL = 'home' # URL redirecting after a successful authentication
LoginView_form.html
now, we need to create template LoginView_form.html and add the following line to display our login form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <html> <head> <title>LoginView</title> </head> <body> <form method="POST">{% csrf_token %} <!-- form variable --> {{ form.as_p }} <input type="submit" name="sumbit"> </form> </body> </html> |
http://127.0.0.1:8000/login/ page:

If the form login is successful, the browser will redirect to /home.