2011-12-19 89 views
3

我有一个表单,我想输出为自定义HTML。我forms.py:django自定义窗体选择标记

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')) 

Django documentation它演示了如何输出自定义HTML。但是显然下面的模板代码不会为选择下地干活:

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

我如何控制选择字段我ModelChoiceFields输出?

+0

oops - 固定错字。 – 2011-12-19 22:00:55

+0

这里你有一个很好的起点:http://tothinkornottothink.com/post/10815277049/django-forms-i-custom-fields-and-widgets-in-detail – maazza 2013-11-20 11:27:49

回答

1

为了更改Django呈现列表项的方式,您需要重写该字段的小部件。

请参阅文档中的Customizing widget instances

Overriding the default field types or widgets

最后,如果这不能给你足够的控制,你可以编写自己的自定义小部件。以下是使用键值对的example of a custom widget。但是,您应该关注的唯一部分是render()方法。您可以扩展内置列表小部件,覆盖render()方法并使其吐出所需的html。

+0

是的 - 这帮助了很多。我选择了自定义小部件,它可以根据需要对html进行尽可能多的控制。 Widget.attrs参数证明特别有用。 – 2011-12-20 16:50:25

6

我想你可以自己构造html。

<select name="{{ form.island_group.name }}"> 
    {% for instance in form.island_group.field.queryset %} 
     <option value="{{ instance.pk }}">{{ instance.name }} yarr</option> 
    {% endfor %} 
</select>