views:

34

answers:

2

Hello, SOvians. I have customized one of my forms and now it does not pass the is_valid() test. No form.errors are visible. Any ideas for where I went wrong?

Form:

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

View:

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 })

Thank you!

+2  A: 

That's probably because you pass request.POST onto userN parameter. If you have keyword argument first it doesn't mean, that request.POST will automatically be put into args - quite contrary, it will be put onto userN. Try this:

form = SearchForm(False, request.POST)
gruszczy
+3  A: 

gruzczy has the right idea, but a better way to do it is to avoid changing the function signature of __init__ in the first place.

def __init__(self, *args, **kwargs):
    self.userN = kwargs.pop('userN', None)
    super(SearchForm,self).__init__(*args,**kwargs)
    ...etc...
Daniel Roseman
Yeah, that's the better idea indeed. I am just that lazy, that only stated, where the error is, not how to make it right :-P
gruszczy