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
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.
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.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:Then
{{form.subject}}
will automatically create<input>
element in the template.Similarly,
{{form.message}}
in the template will create:Though if you really need to get the form field type in the template, you can create a custom template filter like below.
Now, in your template, you need to do something like:
In the above example,
{{form.message|field_type}}
will returnTextInput
.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:
I think another way of dealing with this is to use django crispy forms but I have not tried that yet.
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 modelformsYou can pass any HTML attribute through to the template this way, for example
'placeholder': '[email protected]'
According to https://stackoverflow.com/a/31538555/254553
You can use:
[FIELD]
is your field name.