Python 使用<;optgroup>;使用form.fields.queryset?
是否可以设置表单的ForeignKey字段的queryset,以便它使用单独的queryset并在Python 使用<;optgroup>;使用form.fields.queryset?,python,django,django-forms,django-queryset,Python,Django,Django Forms,Django Queryset,是否可以设置表单的ForeignKey字段的queryset,以便它使用单独的queryset并在中输出它们 以下是我所拥有的: views.py form = TemplateFormBasic(initial={'template': digest.template.id}) form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('nam
中输出它们
以下是我所拥有的:
views.py
form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name')
form.fields['template'].choices = templates_as_choices(request)
def templates_as_choices(request):
templates = []
default = []
user = []
for template in Template.objects.filter(default=1).order_by('name'):
default.append([template.id, template.name])
for template in Template.objects.filter(user=request.user).order_by('name'):
user.append([template.id, template.name])
templates.append(['Default Templates', default])
templates.append(['User Templates', user])
return templates
在我的模板模型中,我有默认模板和用户创建的模板。我希望它们在
框中明显分开,例如
<select>
<optgroup label="Default Templates">
<option>Default 1</option>
<option>Default 2</option>
</optgroup>
<optgroup label="User Templates">
<option>User Template 1</option>
<option>User Template 2</option>
</optgroup>
</select>
默认值1
默认值2
用户模板1
用户模板2
这可以做到吗?我以前在表单上不使用外键,而是使用外键 带有选项的字符域支持optgroup。您需要有以下格式的选项: (‘第一组’、(‘一’、‘雅达’、(‘二’、‘雅达’))、(‘第二组’、(‘三’、‘贝佩蒂’、(‘四’、‘博佩蒂’)))
选项也可以是可调用的。因此,我创建了自己的函数来遍历这些模型并构建一个元组,如上图所示。我能够使用上给出的示例来理解它 views.py
form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('name')
form.fields['template'].choices = templates_as_choices(request)
def templates_as_choices(request):
templates = []
default = []
user = []
for template in Template.objects.filter(default=1).order_by('name'):
default.append([template.id, template.name])
for template in Template.objects.filter(user=request.user).order_by('name'):
user.append([template.id, template.name])
templates.append(['Default Templates', default])
templates.append(['User Templates', user])
return templates
美好的正是博士点的!我正在寻找一种方法来管理表单.fields['field'].queryset,使其成为一种自定义的.chooses,我完全忘记了。伟大的