使用内置总是更好。您还可以使用Field.initial
为该字段设置初始值。 Documetation是here
定义一个选项并将其设置在模板上(可能使用javascript)要困难得多。
UPDATE:
class MyStaffForm(forms.Form):
<your form structure here>
...
<end of your form structure>
def Myview(request):
....
staffs = Staff.objects.filter(staff__company=comp)
#override form class to add a new form field
MyStaffForm.base_fields['staff']=forms.ChoiceField(choices=[[(s.id, s) for s in staffs], initial=staff[0].id)
这是你如何处理表单类。但是使用forms.ChoiceField
覆盖基本Form类并不是一个好的选择,因为您使用查询集来定义选择。因此,使用更新ModelChoiceField
,而不是
MyStaffForm.base_fields['staff']=forms.ModelChoiceField(queryset=staffs, initial=staff[0])
Django会处理验证和形式的初始化休息...
答案... – FallenAngel