'Django Admin Login Form
How do I change the login form used by django admin (want to add a captcha field)? I am using the cookiecutter template and have followed the suggestions in other SO answers, and guides:
forms.py
class AuthAdminForm(AuthenticationForm):
captcha = ReCaptchaField(widget=ReCaptchaV3)
show_something_different = forms.TextInput()
class Meta(AuthenticationForm):
fields = ('email', 'password', 'show_something_different', 'captcha')
urls.py
from django.contrib import admin
from myapp.forms import AuthAdminForm
admin.autodiscover()
admin.site.login_form = AuthAdminForm
admin.site.login_template = 'admin/login.html'
urlpatterns = [
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
...]
I was able to add admin/login.html to my templates dir and extend it. This works to add the google js to the header (can see it in source). But the captcha field and my dummy extra field don't show up.
Solution 1:[1]
I was on the right track, but what caught me out is that the login.html template doesn't render every field present in the form (this is why my dummy test field never showed up). So instead of extending login.html, I copied the entire contents to my own file in templates/admin/login.html, then added the captcha field manually:
<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
<div class="form-row">
{{ form.captcha }}
{{ form.username.errors }}
{{ form.username.label_tag }} {{ form.username }}
</div>
base.html can be extended like this:
{% block extrahead %}
<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-xxx');
</script>
{% endblock %}
Now, finally, captcha is on my admin login page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | womblerone |
