基于 Django class 的视图。对不同的 url 使用相同的自定义 class

Django class based views. Use same custom class for different url

我想知道是否可以只为我在 django 中的视图创建一个自定义 class,它可能对不同的 url 有效。

例如:

#urls.py 
url(r'^$', CustomClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomClass.as_view(), name='other')

#views.py
CustomClass(View):
    # for / url
    def first_method(self, request):
        pass
    # for other_url/
    def second_method(self, request, example):
        pass

我已经阅读了有关基于 class 的视图的文档,但在示例中只讨论了一个 url... https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/

所以,我想我必须为每个 url 创建一个 class。但是对于不同的 url?

,可以使用不同的方法使用相同的 class

您不需要为不同的网址创建不同的 classes。虽然在不同的网址中使用相同的 class 是多余的,但您可以这样做:

url(r'^$', CustomClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomClass.as_view(), name='other')

正是你在做什么。在某些情况下,您有想要使用的泛型 class(来自 generics module/package 的泛型,或者 OOP 意义上的泛型)。举个例子:

url(r'^$', CustomBaseClass.as_view(), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', CustomChildClass.as_view(), name='other')

甚至是相同的 class,只是配置不同(关于通用 classes(从 View 降序):接受的命名参数取决于它们在 class):

url(r'^$', AGenericClass.as_view(my_model=AModel), name='index'),
url(r'^other_url/(?P<example>[-\w]+)$', AGenericClass.as_view(my_model=Other), name='other')

总结 在使用通用视图或传递任何类型的可调用对象时,您完全没有限制,在使用 url.