Class Based Views Part 2: ListView and FormView

The ListView and FormView class based generic views are the first look we have at generic views with some power behind them which can really save us some code. The ListView is great for showing content and paginating said content with very little effort. While the FormView is great for dealing with class based forms without having to deal, to much, with the underlying request itself.
todo/urls.py
from django.views.generic import ListView

from views import DisplayTaskView, DisplayTaskRedirectView, SuggestionView
from models import Task

url(r'^suggest/$', SuggestionView.as_view()),
url(r'^$', ListView.as_view(
                    model=Task, 
                    paginate_by='5',
                    queryset=Task.objects.all(),
                    context_object_name="tasks",
                    template_name='todo/index.html')),
todo/views.py
from django.views.generic.edit import FormView

from forms import TaskForm

class SuggestionView(FormView):
    form_class = TaskForm 
    success_url = "/"
    template_name = "todo/suggest.html"

    def form_valid(self, form):
        print(self.request.POST['name'])
        print(self.request.POST['title'])
        return super(SuggestionView, self).form_valid(form)

template/todo/index.html

{% extends "base.html" %}

{% block content %} <ul> {% for task in tasks %} <li><a href="{% url task task.id task.slug %}">{{ task.title }}</a></li> {% endfor %} </ul> <div class="pagination"> <ul> {% if paginator.has_previous %} <li><a href="?page={{ paginator.previous_page_number }}">Previous</a></li> {% endif %} {% for pg in paginator.page_range %} {% if paginator.number == pg %} <li class="active"><a href="?page={{ pg }}">{{ pg }}</a></li> {% else %} <li><a href="?page={{ pg }}">{{ pg }}</a></li> {% endif %} {% endfor %} {% if paginator.has_next %} <li><a href="?page={{ paginator.next_page_number }}">Next</a></li> {% endif %} </ul> </div> {% endblock %}

comments powered by Disqus