我想知道是否可以在 django 中为我的 View 创建一个对不同 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
我已阅读有关基于类的 View 的文档,但在示例中仅讨论单个 url... https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/
所以,我想我必须为每个网址创建一个类。但是否可以对不同的 url 使用具有不同方法的同一个类?
最佳答案
您不需要为不同的网址创建不同的类。尽管在不同的 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')
摘要在使用通用 View 时没有任何限制,或者在使用 url
时传递任何类型的可调用对象。
关于基于 Django 类的 View 。对不同的 url 使用相同的自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226227/