Ekin Ertaç
Ekin Ertaç

Reputation: 335

how to get form field's field type

I want to get field's model type or form type in Django's ModelForm.

models.py

class Offer(models.Model):
    title = models.CharField(max_length=255)
    start_date = models.DateField()

forms.py

class OfferForm(forms.ModelForm):
    class Meta:
        model = Offer

add_offer.html

{% for form in offer_form %}
    {% if form.field_type??? = 'DateField' %}
        {# add some class or something ??? #}
    {% endif %}
{% endfor %}

In python console everything is pretty good. I mean

print field.__class__.__name__
>>> 'DateField'

but i want to create template tag and results are here:

print field.__class__.__name__
>>> 'BoundField'

what can i do about that ?

Upvotes: 0

Views: 1602

Answers (3)

Mike_Zgz
Mike_Zgz

Reputation: 1

 {% if 'date' in field|field_type %}
       {% render_field field class="form-control is-valid" type="date" %}
 {% else %}
       {% render_field field class="form-control is-valid" %}
 {% endif %}

¡Hope this helps!

Upvotes: 0

esperyong
esperyong

Reputation: 11

>>> f.formfield().widget
<django.forms.widgets.TextInput object at 0x1125fc690>
>>> f.formfield().widget
<django.forms.widgets.TextInput object at 0x1125fc710>
>>> dir(f.formfield().widget)
['__class__', '__deepcopy__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_format_value', 'attrs', 'build_attrs', 'id_for_label', 'input_type', 'is_hidden', 'is_localized', 'is_required', 'media', 'needs_multipart_form', 'render', 'subwidgets', 'value_from_datadict']
>>> f.formfield().widget.attrs
{u'maxlength': '10'}
>>> f.formfield().widget.input_type
u'text'
>>> 

so i think you can use {{ login_form.username.field.widget.input_type }}

Upvotes: 1

HankMoody
HankMoody

Reputation: 3174

Django wraps form fields in templates with the BoundField class. To access proper field class use BoundField's field attribute. Example:

{{ login_form.username.field }}

To access widget:

{{ login_form.username.field.widget }}

Note that you wont be able to access field's class in template. All identifiers starting with an underscore are not accessible in templates.

If you want to customize form rendering, then you have at least these options:

  1. Assign chosen widgets to form fields. If any of Django widgets doesn't provide functionality you want, then you need to create an own widget (usually subclassing builtin widget).

  2. Use different HTML templates to render particular form fields. This is rather a lot of work to write all those templates, but usually pays up, because gives a lot of flexibility.

  3. Find a library, that allows to use HTML templates from #2 (on djangopackages.com maybe).

Upvotes: 1

Related Questions