[Django]-Get the type of field in django template

43👍

According to https://stackoverflow.com/a/31538555/254553

You can use:

{{ [FIELD].field.widget.input_type }}

[FIELD] is your field name.

10👍

I don’t think you need to worry about the field_type. Django will itself handle that for you depending on the form field.

Lets say we have a ContactForm like:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

Then {{form.subject}} will automatically create <input> element in the template.

<input id="id_subject" type="text" name="subject" maxlength="100" />

Similarly, {{form.message}} in the template will create:

<input type="text" name="message" id="id_message" />

Though if you really need to get the form field type in the template, you can create a custom template filter like below.

from django import template

register = template.Library()

@register.filter(name='field_type')
def field_type(field):
    return field.field.widget.__class__.__name__

Now, in your template, you need to do something like:

{{form.field_name|field_type}}

In the above example, {{form.message|field_type}} will return TextInput.

3👍

If you want to access the field type then refer to this answer.
If you want to override the default type of the field, use attrs parameter when defining the widget for the field.
Eg.

field_name = forms.CharField(widget=forms.Textarea(attrs={'type': 'custom type'}))

Also note that you can pass any key value pair to attrs and they will be used as attributes in the html tag when the form is rendered.

2👍

I also had this problem. I used Django Widget Tweaks to add classes (https://github.com/kmike/django-widget-tweaks).

Then you can do something like this:

    {% for field in form %}
     <div class="form-group {% if field.errors %}has-error {% endif %}">    
        {% render_field field class="form-control" %}
        {% if field.errors %}
        <span class="help-block">{{ field.errors.0 }}</span>
        {% endif %}
    </div>
   {% endfor %}

I think another way of dealing with this is to use django crispy forms but I have not tried that yet.

👤Magda

0👍

You are able to override the __init__ method of the form in order to pass attributes to the HTML without having to know the type of field. Works with both standard forms and modelforms

class CoolForm(forms.Form):
    field_name = forms.CharField(...)

    def __init__(self, *args, **kwargs):
        super(CoolForm, self).__init__(*args, **kwargs)
        self.fields['field_name'].widget.attrs = {
            'class': 'form-control'
        }

You can pass any HTML attribute through to the template this way, for example 'placeholder': 'email@exam.pl'

Leave a comment