gpt4 book ai didi

python - use_required_attribute() 缺少 1 个必需的位置参数 : 'initial' django forms

转载 作者:行者123 更新时间:2023-12-04 23:39:20 29 4
gpt4 key购买 nike

我写了一个动态表单:

class VoteForm(forms.Form):
def __init__(self, *args, **kwargs):
question = kwargs.pop('instance', None)
super().__init__(*args, **kwargs)

if question:
if question.allow_multiple_votes:
choice_field = forms.ModelMultipleChoiceField(queryset=question.choice_set)
else:
choice_field = forms.ModelChoiceField(queryset=question.choice_set)
choice_field.widget = forms.RadioSelect
choice_field.label=False
choice_field.empty_label=None
choice_field.error_messages={'required': _('No choice selected.'),
'invalid': _('Invalid choice selected.')}
self.fields['choice'] = choice_field

如果没有 RadioSelect 小部件,一切似乎都可以正常工作,但是使用它会出现以下错误:

TypeError: use_required_attribute() missing 1 required positional argument: 'initial'

最佳答案

在创建字段后设置小部件时,它必须是小部件实例,而不是类本身。但是你必须自己设置选择:

   choice_field.widget = forms.RadioSelect(choices=...)

最好,您可以在构建字段时提供小部件类:
   choice_field = forms.ModelChoiceField(queryset=question.choice_set, widget=forms.RadioSelect)

关于python - use_required_attribute() 缺少 1 个必需的位置参数 : 'initial' django forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42745403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com