django login redirect
To implement a login redirect in Django, you can follow these steps:
- Import the necessary modules:
from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy
Create a login view by subclassing the
LoginView
class:class CustomLoginView(LoginView):
template_name = 'login.html'
In your
urls.py
file, define the URL pattern for the login view:from .views import CustomLoginView
urlpatterns = [
path('login/', CustomLoginView.as_view(), name='login'),
]
In your
settings.py
file, specify the URL to redirect to after a successful login:LOGIN_REDIRECT_URL = 'home'
Optionally, you can also specify the URL to redirect to after a user logs out:
LOGOUT_REDIRECT_URL = 'login'
In your login template (
login.html
), make sure to include the form for user input and submit button:<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
Finally, you can customize the login view by adding any additional functionality or styling as per your requirements.
Note: Make sure you have the necessary templates and HTML files in place for the login and redirect pages.