我已经自定义了一个表单,现在它没有通过is_valid()测试。没有form.errors是可见的。我出错的地方有什么想法吗?
形式:
class SearchForm(forms.Form):
param = forms.CharField(required=False, max_length = 500, label = 'Search for')
sets = forms.ModelMultipleChoiceField(queryset=Set.objects.all())
onlyDiffer = forms.BooleanField(required=False, label = 'Display varying only')
def __init__(self, userN = False, *args, **kwargs):
super(SearchForm,self).__init__(*args,**kwargs)
self.userN = userN
self.fields['sets'].queryset=Set.objects.filter(Q(owner = None) | Q(owner=self.userN))
查看:
def search(request):
template = 'search.html'
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
(..do search..)
else:
return direct_to_template(request, template, {'form' : SearchForm(), 'errors' : form.errors})
else:
usr = request.user
form = SearchForm(usr)
return direct_to_template(request, template, { 'form': form })
谢谢!
答案 0 :(得分:3)
gruzczy有正确的想法,但更好的方法是避免首先更改__init__
的函数签名。
def __init__(self, *args, **kwargs):
self.userN = kwargs.pop('userN', None)
super(SearchForm,self).__init__(*args,**kwargs)
...etc...
答案 1 :(得分:2)
这可能是因为您将request.POST传递给userN参数。如果你首先有关键字参数并不意味着,那个request.POST将自动被放入args - 相反,它将被放到userN上。试试这个:
form = SearchForm(False, request.POST)