How do I create a Django ListView with FormMixin?

I have a working ListView with template. I want to filter the list based on the contents of a form, something like:

class SampleListView(FormMixin, ListView):
    model = Sample
    paginate_by = 15
    form_class = LookupForm

    def get_queryset(self):
        samples = Sample.objects.all()
        # filter based on validated form contents
        form = self.get_form()
        if form.is_valid():
            samples = samples.filter(some_property__gte=form.cleaned_data['sample_number']) 
        return samples

class LookupForm(forms.Form):
    sample_number = IntegerField(widget=NumberInput)

The template shows the form as:

<form action="" method='get'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Query samples'>
</form>

This renders the page with my list and form, but the form always seems to be invalid. How can I integrate the validated form with my ListView? Is this the Avoid anything more complex? That is, should I just not be trying to put the FormMixin and ListView together?

Вернуться на верх