The website I'm building has a login form as part of the base.html template that all the other templates extend; as a result of this I need to somehow handle login/logout logic on every single page.
Currently each page is loaded in a separate view so what is the best and most DRY way of implementing this? all the tutorials I'm reading have the login page separated.
Edit:
My original method was making the forms action always load the index and the pretty much worked however I was annoyed by the fact that I couldn't redirect the user back to wherever they were before they logged in.
afterwards I decided to redesign the form as a Django ModelForm so that I could raise validation errors which I didn't manage to do before but now the template only has the ModelForm object when it is rendered through the index view so the input boxes aren't even rendered on other pages..
You can put a check around your login form code in your template.
You can put the login template in a base_login.html
and extend it on every page.
A sample base template code:
{% if not user.is_authenticated %}
<form action="{% url my_login_url %}" method="POST">
{% csrf_token %}
<input id="username_field" name="username" type="text" />
<input id="password_field" name="password" type="password" />
<button type="submit">Login</button>
</form>
This login form will be displayed only if the user is not authenticated.
Then write a view for login
page and a LoginForm
to handle the login process.
views.py
class LoginView(FormView):
...
your login and redirection logic here
...
forms.py
class LoginForm(forms.Form):
username = ..
password = ..
...
your form validations and other logic
...
So, be it any page, login form will be displayed only if user has not loggedin and all these login requests will go to your LoginView
only.
You don't need to worry about handling the login logic in each view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With