From Classy Class Based Views
Render some list of objects, set by
self.querysetcan actually be any iterable of items, not just a queryset.
There are 16 attributes for the
ListView but only 2 types are required to make the page return something other than a 500 error:
- Template Name
You have a choice of either using
queryset to specify what data to return. Without it you get an error.
Model attribute gives you less control but is easier to implement. If you want to see ALL of the records of your model, just set
model = ModelName
However, if you want to have a bit more control over what is going to be displayed you’ll want to use
queryset which will allow you to add methods to the specified model, ie
queryset = ModelName.objects.filter(field_name='filter')
If you specify both
queryset takes precedence.
Template Name Attributes
You have a choice of using
template_name allows you to directly control what template will be used. For example, if you have a template called
list_view.html you can specify it directly in
template_name_suffix will calculate what the template name should be by using the app name, model name, and appending the value set to the
In pseudo code:
For an app named
rango and a model named
_test would resolve to
If you want to return something interesting you’ll also need to specify
- allow_empty: The default for this is true which allows the page to render if there are no records. If you set this to
falsethen returning no records will result in a 404 error
- context_object_name: allows you to give a more memorable name to the object in the template. You’ll want to use this if you want to have future developers (i.e. you) not hate you
- ordering: allows you to specify the order that the data will be returned in. The field specified must exist in the
querysetthat you’ve used
- page_kwarg: this indicates the name to use when going from page x to y; defaults to
namebut overriding it to something more sensible can be helpful for SEO. For example you can use
pageif you’ve got a page that has a bunch of names
- paginate_by: determines the maximum number of records to return on any page.
- paginate_orphans: number of items to add to the last page; this helps keep pages with singletons (or some other small number
- paginator_class: class that defines several of the attributes above. Don’t mess with this unless you have an actual reason to do so. Also … you’re not a special snowflake, there are literal dragons in down this road. Go back!
A visual representation of how
ListView is derived can be seen here:
ListView CBV is a powerful and highly customizable tool that allows you to display the data from a single model quite easily.