2. Reinout van Rees
• Nelen & Schuurmans
• Django
• Geo stuff, graphs, loads of python libs
• Water management
• http://reinout.vanrees.org
• @reinoutvanrees
3. Great 1.3 feature: CBV
(class based views)
• Models are classes, so why not views?
• Django 1.3+
• Bad PR: “class based generic views”
• Question: who uses generic views?
4. Classes and objects:
theory
• “Encapsulation”: everything in one place
instead of all over the place.
• “Inheritance”: inherit and change/add a
couple of things. Helps with reuse and
DRY.
5. Function based view
example
def _expensive_calculation(request):
# Calculate something and cache the result.
return 'something'
def some_view(request):
template = 'my_app/someview.html'
data = _expensive_calculation(request)
return render_to_response(
template,
{'data': data},
context_instance=RequestContext(request))
6. Class based view
example
class SomeView(TemplateView):
template_name = 'my_app/someview.html'
def _expensive_calculation(self):
# Calculate something and cache the result.
# You can use self.request!
return 'something'
def get_context_data(self, **kwargs):
return {'data': self._expensive_calculation()}
7. Hooking up in urls.py
urlpatterns = patterns(
...
url(r'^function_based_view/$',
'my_app.views.some_view',
name='function_based_view'),
url(r'^class_based_view/$',
my_app.views.SomeView.as_view(),
name='class_based_view'),
...
8. Edit views
class ProcessFormView(View):
"""
A mixin that processes a form on POST.
"""
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(
self.get_context_data(form=form))
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
9. Behind the scenes
• A whole lot of of “mixin classes”.
• A huge stack of ‘em.
• Quite numerous.
• Mixed together.
• Lots of places to look and debug.
10. Documentation
• Currently the code is a better source of
documentation than the code.
• So look in django/views/generic/*.py
• Basic suggestion: find out how to use the
one or two you use daily.
12. Feature request
• No more hand-made context dict
• But an object
• Basically: {‘view’: self}
• => {{ view.number_of_kittens }}
13. Questions?
(And a Dutch advertisement I’m sneaking in
while you’re all asking questions)
• Wij bij Nelen & Schuurmans zoeken weer
nieuwe collega’s :-)
• 40 m/v bedrijf, 9 django.
• Veel open source, pypi, sinds kort github.
• Hartje Utrecht. Vlak bij een ijskraam.
• Schiet me aan (of reinout@vanrees.org)