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

标签 python django

这是表格

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

我需要根据我在查询集中获得的内容在标题字段中设置选择值,该怎么做??

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

最佳答案

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>

关于python - Django Form ChoiceField 在 View in Form initial 中设置选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893324/

相关文章:

python - 哪个开销更大 : Creating a new socket each time or maintaining a single socket for data transfer

python - 在 PyPy 下安装 Python eggs

django - 从前端使用 AJAX 查询 Celery 以了解创建的任务是否完成的最佳方法?

django - 快速问题 django 中的 : how to set *. domainname.com url

Python 在新实例中缓存以前的对象属性

python - 如何删除包含 '0' 的行

python - 如何根据其他列中的值选择 pandas 数据框中的行以及如何为特定列中的每个不同值选择一行

python - Django WSGI Apache VirtualHost,返回 404 错误

python - 如何从 python 中的旧字典中创建新的字典列表?

Django 存储 s3 媒体网址为 https ://instead of http://