I have been using function based views for quite some time but never used class based views until now. My current project requires a lot of common code across multiple views and hence I am exploring class based views so that I can use inheritance.
My requirement is to direct a url to a particular function in the class. Something similar to what can be done on django admin. In Django admin, I have used get_urls method in a class inherited from ModelAdmin to point a url to a class method.
def get_urls(self):
try:
from django.conf.urls.defaults import patterns, url
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
url(r'^myurl/(?P<obj_id>\d+)/$',
self.admin_site.admin_view(self.myFunction),
name="my_function"),
)
return my_urls + urls
except Exception, e:
logger.error(e)
The method myFunction simply calls a method in views.py and passes the request object and the object id. I documentation is here
Is it possible to do a similar thing with class based views? From my search so far I couldn't find any documentation which shows the possibility of passing a function pointer to the as_view method, the way we can do the admin_view method. Please guide me or point me at the right documentation.
as_viewmethod should do the work. Something likeurl(r'^myurl/(?P<obj_id>\d+)/$', MyClassBasedView.as_view(), name="my_function"),)TemplateView? I intend to map urls to my custom class methods.as_viewworks with all CBVs; they all inherit fromdjango.views.generic.Viewclass; you can use it with your own custom classes inheriting from either the base or other provided classes.