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?
Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django. views. generic, and every generic view is one of those classes or a class that inherits from one of them.
Django views are Python functions that takes http requests and returns http response, like HTML documents. A web page that uses Django is full of views with different tasks and missions. Views are usually put in a file called views.py located on your app's folder.
Django Templates are used to create HTML interfaces that get rendered with a Django view. A TemplateView is a generic class-based view that helps developers create a view for a specific template without re-inventing the wheel. TemplateView is the simplest one of many generic views provided by Django.
The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because django allows something you are doing generically you shouldn't do it, particularly not when your code becomes not to your like.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With