Login Required Modal with Django
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.
Recent TILs
X (Twitter) Automation with Python
Automating social media accounts can be annoying, especially because of the shenanigans Big Social put us through to obtain our API keys. Here is an updated…
Dockerize your Gatsby Projects
JavaScript-based projects tend to rot quickly. Very often, when I come back to them a few months later, nothing works. Today simply running my Gatsby blog after…
Google Login with Django Allauth
I often find myself needing to implement Google OAuth in Django projects but keep forgetting the exact steps. So, I'm documenting the process here for future…