I have a a form that I want to output as custom HTML. My forms.py:
from django import forms
from cdrs.models import Localitymayor
class SearchForm(forms.Form):
genus = forms.CharField(max_length=100)
species = forms.CharField(max_length=100)
island_group = forms.ModelChoiceField(queryset=Locality.objects.values_list('islandgroup', flat=True).distinct('islandgroup').exclude(islandgroup="n/a").order_by('islandgroup'))
island_name = forms.ModelChoiceField(queryset=Locality.objects.values_list('islandname', flat=True).distinct('islandname').exclude(islandname="n/a").order_by('islandname'))
In the Django documentation it demonstrates how to output custom html. However the template code below obviously doesn’t work for the select fields:
<form action="/search/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.genus.errors }}
<label for="id_genus">Genus:</label>
{{ form.genus }}
</div>
...
<div class="fieldWrapper">
{{ form.island_group.errors }}
<label for="id_island_group">Island Group:</label>
{{ form.island_group }}
</div>
...
</form>
How do I control the output of select fields for my ModelChoiceFields?
In order to change how Django renders list items you need to override that field’s widget.
See the Customizing widget instances in the documentation.
And Overriding the default field types or widgets.
Finally, if this doesn’t give you enough control, you can write your own custom widget. Here is an example of a custom widget for working with key-value pairs. However, the only part you should be concerned with is the
render()method. You could extend a built in list widget, override therender()method and make it spit out the html you want.