very simple view functions

Sometimes you have a bunch of really simple view functions in your django project (yes, this is for your, bitprophet! zwinkerndes Gesicht). View functions that are actually not more than just a rendertoresponse call - take a template, take some data from the request, stuff them in and render a response. It's rather boring to write them down and it breaks the DRY principle. So what to do? Write your own generic view.

from django.core.extensions \
    import render_to_response

def simple_view(request, template, **kwargs):
    return render_to_response(
        template, kwargs)

That's all. A simple and nice view function that just does that - render a template. It even can be fed with context variables from the urlpattern. Use it like this in your urlconf:

urlpatterns = patterns('',
(r'^page/(?P<arg>.*)/$', 'cool.simple_view',
     {'template': 'app/mytemplate'}),
)

That way a /page/foo/ view would be routed to the 'app/mytemplate' template with a context that just includes the variable 'arg' with the value 'foo'. And you never will need to write those simple_view functions again. For extra spices you could throw in a context_instance = DjangoContext(request) into the rendertoresponse call to even get the authenticated user and stuff like that from the request.

tags: Django, Programmierung, Python