【问题标题】:Django class based views. Use same custom class for different url基于 Django 类的视图。对不同的 url 使用相同的自定义类
【发布时间】:2015-12-11 14:50:10
【问题描述】:

我想知道是否可以只为我在 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 创建一个类。但是有可能对不同的url使用同一个类和不同的方法吗?

【问题讨论】:

    标签: django django-class-based-views


    【解决方案1】:

    您不需要为不同的 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')
    

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

    【讨论】:

    • 谢谢。我将尝试您的第二个或第三个示例。因为在第一个示例中,我不知道如何使用同一个类为不同的 url 调用不同的方法......可能在 as_view(method='first_method') 中有一个参数
    • 泛型旨在用于第二个示例(通过继承)甚至第三个示例(虽然我不会这样做,但这是允许的)。
    • 感谢您的建议!那么,每个网址都有一个独立的类更好吗?我想学习最佳实践...
    • 恕我直言,也许我不会使用第三个。我不喜欢在 urls.py 中导入模型类。但是,这只是我的口味。
    猜你喜欢
    • 2018-03-12
    • 2018-07-18
    • 2013-10-09
    • 2012-12-28
    • 2013-02-15
    • 2023-03-19
    • 2016-10-16
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多