【问题标题】:django-rest-framework: Can Ihave multiple templates per ViewSet?django-rest-framework:每个 ViewSet 可以有多个模板吗?
【发布时间】:2020-07-07 01:30:04
【问题描述】:

我为我的模型创建了一个序列化程序和 ViewSet,并为列表视图添加了一个模板。要查看网页(模板),排序渲染类必须正确,并且需要将TemplateHTMLRenderer 添加到渲染器列表中。

这会导致当想要浏览到特定记录时出现的问题,例如

/mymodel/5

在浏览器中,我也会看到列表视图。

目标是有 1 个 url 为 api (json) 或网页提供列表和详细信息视图。 (/mymodel = 列表,/mymodel/5 = 详细信息)

问题是:如何基于一个 ViewSet 拥有多个模板(列表/详细信息)?

【问题讨论】:

    标签: django-rest-framework django-templates django-rest-viewsets


    【解决方案1】:

    解决方法是重写get_template_names方法,根据正在执行的动作返回模板。

    def get_template_names(self):
        if self.action == 'list':            
            return ['list.html']
        elif self.action == 'retrieve':            
            return ['details.html']
    

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 2017-07-21
      • 2013-11-11
      • 2015-02-12
      • 1970-01-01
      • 2014-05-29
      • 2014-05-13
      • 2018-10-01
      • 1970-01-01
      相关资源
      最近更新 更多