views:

200

answers:

3
+1  Q: 

Form Field API?

I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ?

Thanks

A: 

Presuming you're using HTML here... Because it isn't very clear.

How about giving it an extra class.

And if you didn't know allready, the class attribute will recognise this:

class="hello there you"

as having 3 classes. The class 'hello', the class 'there', and the class 'you'. So if they allready have a class, just add a space and your custom clasname.

Vordreller
+3  A: 

Have a look at the class for each field on your form:

for f_name, f_type in my_form_instance.fields.items():
    print "I am a ",type(f_type)
    # or f_type.__class__

This will produce output similar to <class 'django.forms.fields.BooleanField'>.

You can get the name as a simple string, if you prefer that, with:

print type(f_type).__name__
# produces 'BooleanField'

Edit: Also be careful about the distinction between a field and a widget. There isn't a Checkbox field in Django, but only a CheckboxInput widget, which is the default for a BooleanField. Do you mean to look up the widget (which is very rendering specific), or the field (which has more of a relation to the data type and validation for that form field)? If the widget, you can get the widget type using:

f_type.widget

Hope that helps!

Jarret Hardie
+1  A: 

I am not sure if this is what you want, but if you want to know what kind of field it is going to end up being in the HTML, you can check it with this:

{% for field in form %}
    {{ field.field.widget.input_type }}
{% endfor %}

widget.input_type will hold text, password, select, etc.

P.S. I did not know this until 5 seconds ago. #django irc.freenode.net always has good help.

Paolo Bergantino