0
0
Djangoframework~5 mins

Login view and template in Django

Choose your learning style9 modes available
Introduction

Login views let users enter their username and password to access a website. Templates show the login form on the page.

When you want users to sign in to your website.
When you need to protect parts of your site from public access.
When you want to personalize content for logged-in users.
When you want to track user activity after login.
Syntax
Django
from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = 'login.html'

Use LoginView from Django's built-in auth views to handle login logic.

Set template_name to tell Django which HTML file to show for the login form.

Examples
This example uses a custom template path inside a 'users' folder.
Django
from django.contrib.auth.views import LoginView

class CustomLoginView(LoginView):
    template_name = 'users/login.html'
Here, the login view is added directly to URL patterns with a template specified.
Django
from django.urls import path
from django.contrib.auth.views import LoginView

urlpatterns = [
    path('login/', LoginView.as_view(template_name='login.html'), name='login'),
]
Sample Program

This code creates a login page at '/login/'. The template shows a simple form with username and password fields. The form uses Django's built-in form rendering and includes CSRF protection.

Django
from django.contrib.auth.views import LoginView
from django.urls import path

class MyLoginView(LoginView):
    template_name = 'login.html'

urlpatterns = [
    path('login/', MyLoginView.as_view(), name='login'),
]

# login.html template content:
#
# <!DOCTYPE html>
# <html lang="en">
# <head>
#     <meta charset="UTF-8">
#     <meta name="viewport" content="width=device-width, initial-scale=1.0">
#     <title>Login</title>
# </head>
# <body>
#     <h1>Login</h1>
#     <form method="post">
#         {% csrf_token %}
#         {{ form.as_p }}
#         <button type="submit">Log in</button>
#     </form>
# </body>
# </html>
OutputSuccess
Important Notes

Always include {% csrf_token %} in your login form for security.

Django's LoginView handles user authentication automatically.

You can customize the form by overriding the authentication_form attribute if needed.

Summary

Use Django's LoginView to create login pages easily.

Set template_name to specify your login form HTML.

Include CSRF tokens and use Django's form rendering for security and simplicity.