Login Required Modal with Django
Published on January 21st, 2024
The goal is to show a modal when the user clicks on a link, rather than redirecting him right away to the auth page.
It just seems less confusing.
In a file called includes/signup_required_modal.html
, we add the following code:
{% load static %}
{% load i18n %}
{% if not user.is_authenticated %}
<div id="loginRequiredModal" class="modal fade">
<div class="modal-dialog modal-dialog-centered modal-md">
<div class="modal-content">
...
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.login-required').forEach(function (element) {
element.addEventListener('click', function (event) {
event.preventDefault();
$('#loginRequiredModal').modal('show'); // Trigger the modal
});
});
});
</script>
{% endif %}
Now we need to include our modal code in our base.html
, so it is accessible from everywhere:
...
{% include 'includes/signup_required_modal.html' %}
</body>
...
And that's it.
We can now annotate any link anywhere in the website with the class .login-required
and it will show our modal.
This is an ideal place for fast social login buttons.
Keep in mind this is just an UX enhancement. All the user-only pages should still be redirected server side with something like the @login_required
decorator.