Django Crispy Forms报错:位置参数位于关键字参数之后
解决Django Crispy Forms语法错误:positional argument follows keyword argument
嘿,这个错误其实是Python基础语法规则在搞事情——你在使用Crispy Forms的Div组件时,把位置参数(嵌套的子Div元素)放在了关键字参数(title、css_class这类键值对参数)的后面,Python不允许位置参数跟在关键字参数之后,这就是报错的根源啦!
看你代码里的这段错误写法:
Div(title='', css_class='panel panel-primary', Div(title='Details', css_class='panel-heading'), Div(css_class='panel-body', Field('location', placeholder='Location'), Div('site_type', title="Site Type") ), )
这里title=''和css_class='panel panel-primary'是关键字参数,而后面的两个Div(...)是位置参数,顺序搞反了,才触发了positional argument follows keyword argument的语法错误。
修正后的完整代码
把位置参数(嵌套的子组件)放在最前面,关键字参数放在最后就可以解决问题了:
class EditSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location', 'site_type', 'bgp_as', 'opening_date','last_hw_refresh_date','is_live', 'tel','address','town','postcode', 'regional_manager','regional_manager_tel','assistant_manager','assistant_manager_tel' ,'duty_manager','duty_manager_tel'] def __init__(self, *args, **kwargs): super(EditSiteForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'edit_site_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div( Div(title='Details', css_class='panel-heading'), Div( css_class='panel-body', Field('location', placeholder='Location'), Div('site_type', title="Site Type") ), title='', css_class='panel panel-primary' ) )
简单来说就是一句话:在Python函数/方法调用中,所有位置参数必须出现在关键字参数之前,Crispy Forms的组件调用也得遵守这个规则哦~
内容的提问来源于stack exchange,提问作者AlexW
相关产品推荐
相关产品推荐

