Django Generic Views: Basic Views

Django Generic Views

View

The View class provides simple dispatch functionality for all class-based views. Generally, you want to use a subclass of View, instead of inheriting directly from View, but the approach will always be the same. A class-based view is deployed into a URL pattern using the as_view() classmethod:

urlpatterns = patterns('',
    (r'^view/$', MyView.as_view( answer=42 ) ),
)

When the view is invoked, an instance of your class will be created, and any arguments you provide to the as_view method will be set as instance values.

RedirectView

The RedirectView allows you to generically cause an HTTP redirect (301 or 302). The easiest way to use this class is to pass in arguments when defining a URL:

urlpatterns = patterns('',
    (r'^oldname/(P<id>.*)$', RedirectView.as_view( url="/newname/%{id}s" ) ),
)

This will cause a local URL such as /oldname/45 to redirect to /newname/45, which is useful if you’ve redesigned your URL hierarchy but still need to support the older URIs.

TemplateView

Leave a Reply

Your email address will not be published. Required fields are marked *