skip to Main Content

I am using django forms and I want to use Twitter Bootstrap’s css in my html.
so my template looks like this:

{% for field in form %}
    <div class="form-group">
        {{ field.label_tag }}<!--Same thing as : <label for="{{field.id_for_label}}"></label> -->

        <input type="{{field.type}}" class="form-control" id="{{field.auto_id}}" placeholder="Email">
      </div>
{% endfor %}

I can’t figure out out to get the type value. {{field.type}} .

Is there any way to get the type of the input field in django templates?

Thanks in advance

Update:
The reason I am asking this question is because I want to be able to apply bootstrap classes to the input element. But in Bootstrap3, to use the default css for input types you would have to add form-control class to the input element like so: <input type="text" class="form-control" id="{{field.auto_id}}" placeholder="">.

If I use django’s field {{field}} then I can’t add the form-control class.
I hope this clarifies some things.

I also saw this app https://github.com/dyve/django-bootstrap3 that looks like it does what I wanted to do. It surprises me that django doesn’t allow accessing the form type to allow more flexibility.

5

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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 protected]'

    Login or Signup to reply.
  5. According to https://stackoverflow.com/a/31538555/254553

    You can use:

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

    [FIELD] is your field name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search