Django Crispy 表单和选项组

Django Crispy Forms and Option Groups

我一直在 Crispy Forms 文档和一般网络上搜索此问题的答案。

Crispy Forms 可以使用 forms.Select 小部件在 ChoiceField 中输出 <optgroup> 吗?还是我必须将数据置于上下文中并在模板中以老式方式构建表单?

谢谢!

choices docs 举例说明如何对您的选择进行分组。

MEDIA_CHOICES = (
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
)

如果你这样做,那么 select 小部件应该输出 optgroups,无论你是否使用 crispy 形式。

USER_GENERATED_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=True))
DEFAULT_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=False))

# Set the initial TEMPLATE CHOICES list to include the Default Templates choice object
TEMPLATE_CHOICES = [('Default Templates',([[template.id, template.name] for template in DEFAULT_TEMPLATES]))]

# If there are user generated templates, append the TEMPLATE_CHOICES list to include them
if USER_GENERATED_TEMPLATES.count() > 0:
    TEMPLATE_CHOICES.append(('Saved Templates',([[template.id, template.name] for template in USER_GENERATED_TEMPLATES])))

# Set the 'template' form field to a ChoiceField using the Select widget populated by the TEMPLATE_CHOICES list.
self.fields['template'] = forms.ChoiceField(widget = forms.Select(), choices=TEMPLATE_CHOICES)