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

时间:2015-12-11 14:50:11

标签: django django-class-based-views

我想知道是否可以在django中为我的视图创建一个自定义类,可以对不同的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

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

所以,我想我必须为每个网址创建一个类。但是对于不同的URL,可以使用不同方法的相同类吗?

1 个答案:

答案 0 :(得分:2)

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

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

正是你正在做的事情。在某些情况下,您有一个要使用的泛型类(来自generics模块/包的通用类,或者在OOP意义上的泛型)。比如说,一个例子:

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

甚至是只有不同配置的同一个类(关于泛型类(从View下降):接受的命名参数取决于它们在类中的定义方式):

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时,在使用通用视图或传递任何类型的可调用时,您完全没有任何限制。

相关问题