Django TypeError:__ init __()得到关键字参数'required'的多个值

Luc*_*s03 1 django django-forms

对我来说,找出问题可能为时已晚.我有一个简单的形式forms.py:

class ImportPortfolioForm(forms.Form):
    file = forms.FileField(required=True)
    price_per_share = forms.BooleanField('Price per Share', required=False, initial=True,
                                   help_text="If not checked, total cost is expected in Price column.")
Run Code Online (Sandbox Code Playgroud)

这是html:

<form method="post" action="" class="wide" class="form-horizontal" enctype="multipart/form-data">
    <div class="col-md-6">
    {% csrf_token %}
    {% bootstrap_form form %}
    <button type="submit" class="btn btn-primary">Import</button>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

这是views.py:

if request.method == 'POST':
    form = ImportPortfolioForm(request.POST, request.FILES)
    if form.is_valid():
        data = form.cleaned_data
        # work with file ...
else:
    form = ImportPortfolioForm()
Run Code Online (Sandbox Code Playgroud)

如果我尝试加载表单网址,我收到错误:

TypeError: __init__() got multiple values for keyword argument 'required'
Run Code Online (Sandbox Code Playgroud)

如果我删除需要这样:

class ImportPortfolioForm(forms.Form):
    file = forms.FileField(required=True)
    price_per_share = forms.BooleanField('Price per Share', initial=True,
                                         help_text="If not checked, total cost is expected in Price column.")
Run Code Online (Sandbox Code Playgroud)

我可以加载表单网址.如果我添加文件和发送表单,则声明每个字段的场地价格是必需的: 图像表单上传 我不知道为什么会出现这种情况.我想request.POST在表单初始化中以某种方式添加required=True到表单中.但我不知道为什么会这样做或为什么我不能在表格中覆盖它.有任何想法吗?

knb*_*nbk 6

...
price_per_share = forms.BooleanField('Price per Share', required=False, initial=True)
Run Code Online (Sandbox Code Playgroud)

只有模型字段接受标签作为第一个位置参数.表单字段要求您使用label关键字.required是表单字段的第一个参数,因此您将它作为位置参数和关键字参数传递.

通常,您只在表单字段中使用关键字参数.您可能正在寻找的关键字是label:

price_per_share = forms.BooleanField(label='Price per Share', required=False, initial=True)
Run Code Online (Sandbox Code Playgroud)