Alex Rivera | Logout

In plain English, what are Django generic views?

Asked 2010-03-13T06:09:35.133
26

The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one):

https://docs.djangoproject.com/en/1.4/topics/generic-views/

I'm all for improving my life, but what do generic views actually do? It seems like lots of buzzwords are being thrown around, which confuse more than they explain.

Are generic views similar to scaffolding in Ruby on Rails? The last bullet point in the intro seems to indicate this. Is that an accurate statement?

Edit
Report

1 Answer

19

Django generic views are just view functions (regular old python functions) that do things that are very common in web applications.

Depending on the type of app you are building, they can save you from writing a lot of very simple views.

For example, the direct_to_template generic view simply renders a template with the RequestContext (which means the template has access to information on the request, like the current user, etc).

As a simple example, you can go from writing things like this:

# urls.py
url('^some-url/$', some_view)

# views.py
def some_view(request):
    return render_to_response('template_name.html', context_instance=RequestContext(request))

To just this:

# urls.py
url('^some-url/$', direct_to_template, {'template': 'template_name.html'})

# views.py doesn't need any code for this view anymore

There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".

Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.

answered 2010-03-13T06:18:57.607

Your Answer