Django class based views - Direct url to particular method in class

1.5k views Asked by At

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.

1

There are 1 answers

0
Alasdair On BEST ANSWER

The admin views are very different to the rest of Django's class based views for historical reasons, so moving an implementation from one to the other can be tricky.

Regular CBV are meant to be hooked up to a particular url pattern, they aren't designed to dispatch different urls to different views, so implementing a get_urls method doesn't really make sense.