【问题标题】:example template for django rest framework paginationdjango rest 框架分页的示例模板
【发布时间】:2014-08-24 03:03:36
【问题描述】:

我第一次尝试使用 Django REST 框架,看教程没有模板示例,我可以使用什么模板?我试过 template_name = 'authorListAjax.html' 但我得到了这个回复http://imgur.com/fMlyXDN

views.py

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('subject', 'date', 'time_start')  

class AuthorListAll1(ListAPIView):
    template_name = 'authorListAjax.html'
    queryset = Author.objects.all()
    serializer_class = AccountSerializer
    paginate_by = 2
    paginate_by_param = 'page_size'
    max_paginate_by = 100

urls.py

url(r'^ajax/list/$', AuthorListAll1.as_view(), name='ajax_list'),

【问题讨论】:

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


【解决方案1】:

需要设置渲染器:http://www.django-rest-framework.org/api-guide/renderers#templatehtmlrenderer

这意味着添加这一行(告诉 DRF 响应将是 HTML,而不是 JSON):

renderer_classes = (TemplateHTMLRenderer,)

另外,您不能在视图类上设置模板名称;模板名称属于渲染器类。您可以直接在渲染器上设置它,如下所示:

TemplateHTMLRenderer.template_name = 'authorListAjax.html'

或者您可以覆盖 get 方法并将其设置在那里,如下所示:

return Response({'user': self.object}, template_name='authorListAjax.html')

我推荐你第二种方式,因为第一种方式是全局设置模板名称,它可能会给你带来麻烦:)

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2016-06-20
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2014-08-25
    • 2020-10-29
    • 2017-03-24
    • 2017-12-28
    相关资源
    最近更新 更多