2
class CreateCourseForm(ModelForm):
category = forms.ModelChoiceField(
queryset=Category.objects.all(),
empty_label="",
#widget=CustomCourseWidget()
)
class Meta:
model = Course
fields = ('title', 'description', 'category')
def __init__(self, *args, **kwargs):
super(CreateCourseForm, self).__init__(*args, **kwargs)
self.fields['category'].widget.attrs['class'] = 'chzn-select'
self.fields['category'].widget.attrs['data-placeholder'] = u'Please select one'
通過上面的代碼,我得到了列出所有類別對象的選擇框。我正在嘗試添加一個Django Forms和ModelChoiceField:將HTML optgroup元素添加到QuerySet中的特定對象?
<optgroup>VALUE</optgroup>
將HTML元素添加到特定的類別對象(Category.parent == null)。
有誰知道該怎麼做?非常感謝!我已經嘗試將QuerySet轉換爲選擇集(例如http://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/),該工具可以很好地呈現HTML,直到我嘗試將結果保存到發生不匹配的數據庫(ValueError)時爲止。
您在引用,或其變體的方法是做到這一點的方法。恢復到您所擁有的內容,然後發佈堆棧跟蹤以獲取您遇到的錯誤。 –
我已經使用自定義小部件創建了一個解決方案。我會盡快回復我自己的問題。 –