Django Form ChoiceField在View in Form initial中设置选项

时间:2017-12-19 18:44:22

标签: python django

这是表格

class Form(Models.Form):
    title = forms.ChoiceField()

我需要根据查询集中的内容在title字段中设置选项值,怎么做?

def func(request):
    titles = Titel.objects.all() 
    form = Form(initial={ "title": "???titles???"})
    return render('template.html', locals())

2 个答案:

答案 0 :(得分:3)

form = Form()
form.fields['title'].choices = [(title.title, title.title) for title in titles]
form.fields['title'].initial = titles[0].title  # by default first will be selected

因此它将返回包含元组的列表,如

[('title1', 'title1'), (title2, title2), ... , ('title(n)', 'title(n)'),]

对于您的下拉菜单,您将拥有此类选项

<option value="title1">title1</option>

答案 1 :(得分:0)

您应该在 form.ModelChoiceField()

中使用 empty_label 参数

a success b success c success d success