0

使用Django我旨在創建一個帶有「select」字段的表單,並使用db表「TestTable」中的值填充表單。如何控制Django表格中的選擇/選項

TestTable的的領域是:身份證,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> 

如何選擇哪個字段打印在選項標籤?

回答

2

有兩種方法。快速的方法是更改​​__unicode__返回您的TestTable返回您喜歡的字段。但是,您可能只想以當前形式顯示該字段,但不能在其他位置顯示該字段,因此這並不理想。

第二個選項,你可以定義你自己的表單字段。它繼承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')) 
+0

感謝。它完全正常工作。是否有可能設置'

+0

我以爲它已經這樣做了,那是默認設置。你可以仔細檢查每個'

+0

你是對的,它已經在做這件事。 – David

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