Login/Logout(Default)
Configure the Django Authentication URL Routes
Urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
# Login and Logout
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]Login /Logout Link
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'logout' %}">Logout</a>Create a Django Login Template & Form
By default, LoginView will try to render myapp/registration/login.html. So in your templates folder, create a registration folder and inside that create login.html file.
{% extends 'base.html' %}
{% block title %}Login Page{% endblock title %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock content %}
Customize the Django Login View
We can pass some parameters to LoginView, which will help us to have more control over the URL and change the behavior of the view.
Suppose you want the login.html template somewhere else than registration/login.html. For that, you need to pass template name in LoginView.
After a successful login, we need the redirect to the next page. We can set that next page in settings.py by adding the below code –
If we do not set login redirect URL, it will take to default URL /accounts/profile/ which will give TemplateDoesNotExist error.
We can also redirect a user who is already authenticated by setting redirect_authenticated_user parameter to true. ( loginview.as_view, edirect_authenticated_user, auth_views.loginview )
Customize the Django Logout View
If you need to redirect to a template after logout, you can set the template name in LogoutView like this –
And if you want to redirect to a URL after logout, you can set the next page in LogoutView like this –
Or in settings.py file add the Logout Redirect URL.
Note – home is URL name. You can keep it as you want.
Last updated