使用django-crispy-forms拆分表单到带ID的Div时的问题
问题解决方法
你代码里的核心问题是没有将Layout对象赋值给FormHelper的layout属性,而是直接给表单类的self.layout赋值——这在django-crispy-forms中不会生效,因为表单的布局控制逻辑是绑定在FormHelper实例上的。
修改后的代码如下:
class PBForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) # 关键修正:把Layout赋值给helper的layout属性 self.helper.layout = Layout( Div('cc', 'pb_id', css_id="pbid"), Div('closed_r', 'closed_l', css_id="pb-options") ) pb_id = forms.ChoiceField(label='PB', widget=forms.RadioSelect) closed_l = forms.ChoiceField(label='Left Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) closed_r = forms.ChoiceField(label='Right Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) class Meta: model = pb fields = ['cc', 'pb_id', 'closed_r', 'closed_l']
同时需要确认两个前提:
- 已正确安装并配置django-crispy-forms:在
INSTALLED_APPS中添加'crispy_forms',并设置CRISPY_TEMPLATE_PACK(比如'bootstrap4') - 模板渲染表单时使用crispy提供的方式:先加载标签
{% load crispy_forms_tags %},再用{{ form|crispy }}或{% crispy form %}渲染——如果用{{ form.as_p }}这类原生方式,crispy的布局配置不会生效,自然不会生成指定ID的div。
内容的提问来源于stack exchange,提问作者Shreko
相关产品推荐
相关产品推荐

