View
from django.views.generic import View
class ContactList(View):
def get(self):
return HttpResponse("You have no contacts")
from django.views.generic import TemplateView
class ContactList(TemplateView):
template_name = 'index.html' # or define get_template_names()
def get_context_data(self, **kwargs):
context = super(ContactList, self).\
get_context_data(**kwargs)
context['first_names'] = ['Nathan', 'Richard']
return context
View
provides as as_view
methodurlpatterns = patterns('',
(r'^index/$', ContactList.as_view()),
)
kwargs
passed to as_view
can override properties on the View class.args
and .kwargs
inside your classTemplateView
get_context_data()
template_name
, get_template_names()
response_class
render_to_response()
ProcessFormView
form_class
get_success_url()
form_valid(form)
form_invalid(form)
CreateView, UpdateView
model
get_object()
The http_method_names
property defines a list of supported methods
In Django 1.5 this is:
http_method_names = ['get', 'post', 'put', 'delete', 'head',
'options', 'trace']
If you want to support something like HTTP PATCH
, you need to add it to that list in your View subclass
Views will look for a class method named for the HTTP method: get()
is called for GET
, etc.
super()
in your methods: this allows others to mix your View with othersclass EventsPageMixin(object):
"""View mixin to include the Event in template context."""
def get_event(self):
if not hasattr(self, 'event'):
self.event = get_event()
return self.event
def get_context_data(self, **kwargs):
context = super(EventsPageMixin, self).\
get_context_data(**kwargs)
context['event'] = self.get_event()
return context