2016-03-23 42 views
1

对于我来说,找出错误的可能已经太晚了。我有一个简单的形式forms.pyDjango TypeError:__init __()为关键字参数'required'获取了多个值

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.") 

这是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> 

,这是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() 

我得到错误,如果我尝试加载表格网址:

TypeError: __init__() got multiple values for keyword argument 'required' 

如果我删除这样的要求:

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.") 

我可以加载表单url。如果我添加文件和发送表单,它声称每场股票的价格是必需的: image form upload 我不知道为什么会发生这种情况。我猜想在表单初始化中,request.POST以某种方式将required=True添加到表单中。但我不知道它为什么这样做,或者为什么我不能以一种形式覆盖它。有任何想法吗?

回答

5
... 
price_per_share = forms.BooleanField('Price per Share', required=False, initial=True) 

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

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

price_per_share = forms.BooleanField(label='Price per Share', required=False, initial=True) 
+0

就是这样,谢谢! – Lucas03

相关问题