Domen Blenkuš Domen Blenkuš - 3 months ago 13
Python Question

Get field type in Django's login template

I'm trying to create custom template for Django's build-in login view. At the moment it looks like (

registration/login.html
):

<form method="post">
{% csrf_token %}

{% for field in form %}
{% include 'registration/form_field.html' %}
{% endfor %}

<input class="btn btn-primary btn-block" type="submit" value="{% trans "Log in" %}">
</form>


And
registration/form_field.html
file is:

<div class="form-group {% if field.errors %}has-error{% endif %}">
<input class="form-control" name="{{ field.name }}" placeholder="{{ field.label }}" {% if field.data %}value="{{ field.data }}"{% endif %} />
{% if field.errors %}
<span class='text-danger'>{{ field.errors|join:'<br>' }}</span>
{% endif %}
</div>


Everything works as expected, only problem is that password is shown in clear text.

To solve this
type="password"
should be set for
password
field (and
type="text"
for
username
field).

Is it possible to implement this using
field
variable (i.e. something like
{{ field.type }}
)?

Answer

You can implement a PasswordInput widget in your form definition, that will render as a password field with type="password".

class ExampleForm(forms.Form):
    password = forms.CharField(label='Password', 
                               widget=forms.PasswordInput())

In the templates,

{{form.password}}

will render this field, which is the cleanest solution.

You may also access the type of the field (as you wanted), like this:

{{form.fields.password.widget.input_type}}

Note that if you'd like further customization beyond simply rendering the form, there's nothing wrong with just writing your own html for the fields.