如何在 Django Forms 中控制 Select / 选项

How to control Select / Options in Django Forms

我打算使用 Django 创建一个带有 "select" 字段的表单,并使用来自数据库 table "TestTable".

的值填充该表单

TestTable的字段有:id、desc1、desck2、desc3、desc4等...

这是我在 form.py 中的代码:

class TestForm(forms.ModelForm):
    field1 = ModelChoiceField(queryset=TestTable.objects.all().order_by('desc1'))
    class Meta(object):
        model = BlockValue
        fields = ()

这是模板:

<html>
<head><title>TEST PAGE</title></head>

<body>
Test: 
{{ form }} 

</body>
</html>

这里是 view.py:

def test(request):
    form = TestForm()
    return render(request, 'test.html', {'form': form})

当我呈现表单时,结果是:

<tr><th><label for="id_field1">Field1:</label></th><td><select id="id_field1" name="field1">
<option value="" selected="selected">---------</option>
<option value="1">aaaaaaa</option>
<option value="3">bbbbbbb</option>
<option value="2">ccccccc</option>
</select></td></tr>

如何选择选项标签中打印的字段?

有两种方法。快速的方法是将 TestTable__unicode__ return 更改为 return 您喜欢的字段。但是,您可能只想以当前形式显示该字段,而不是其他地方,因此这并不理想。

第二种选择,您可以定义自己的表单域。它继承了ModelChoiceField,但覆盖了label_from_instance方法:

class TestTableModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
         # return the field you want to display
         return obj.display_field

class TestForm(forms.ModelForm):
    type = TestTableModelChoiceField(queryset=Property.objects.all().order_by('desc1'))
class TestForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(*args, **kwargs) # initialize form, which will create self.fields dict
        self.fields['field1'].choices = [(o.id, str(o).upper()) for o in TestTable.objects.all()] # provide a list of tuples [(pk,display_string),(another_pk,display_str),...]
        # display string can be whatever str/unicode you want to show.