基于Django类的视图 - 直接url到类中的特定方法

时间:2022-06-29 19:21:40

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.

我的要求是将url指向类中的特定函数。类似于django admin可以做的事情。在Django admin中,我在从ModelAdmin继承的类中使用了get_urls方法,将url指向了一个类方法。

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

方法myFunction只是调用views.py中的方法并传递请求对象和对象id。我的文档在这里

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_view方法的可能性,我们可以使用admin_view方法。请指导我或指出正确的文档。

1 个解决方案

#1


1  

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.

由于历史原因,管理视图与Django的基于类的视图的其余部分非常不同,因此将实现从一个实现移动到另一个可能是棘手的。

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.

常规CBV旨在连接到特定的url模式,它们不是为不同的视图分配不同的URL,因此实现get_urls方法并没有多大意义。

#1


1  

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.

由于历史原因,管理视图与Django的基于类的视图的其余部分非常不同,因此将实现从一个实现移动到另一个可能是棘手的。

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.

常规CBV旨在连接到特定的url模式,它们不是为不同的视图分配不同的URL,因此实现get_urls方法并没有多大意义。