Django class based view ListView with form

Viewed 34317

The main view is a simple paginated ListView and I want to add a search form to it.

I thought something like this would do the trick:

class MyListView(ListView, FormView):
    form_class = MySearchForm
    success_url = 'my-sucess-url'
    model = MyModel
    # ...

But apparently I got it wrong .. and I can't find how to do it in the official documentation.

Suggestions ?

5 Answers

In Django 2.2 you can do this (it works fine at least with a get-request):

from django.views.generic import ListView
from django.views.generic.edit import FormMixin

from .models import MyModel
from .forms import MySearchForm

class ListPageView(FormMixin, ListView):
    template_name = 'property_list.html'
    model = MyModel
    form_class = MySearchForm
    queryset = MyModel.objects.all()

Use the FormMixin before the ListView. If you want to use the SearchForm in a TemplateView you can do this:

from django.views.generic.base import TemplateView
from django.views.generic.edit import FormMixin

from .models import MyModel
from .forms import MySearchForm

class HomePageView(FormMixin, TemplateView):
    template_name = 'home.html'
    form_class = MySearchForm

Adding forms to index and list views using mixins is covered in the the official documentation.

The documentation generally recommends against this approach. It suggests to instead simply write a bit more python, and code the view manually.

Related