【问题标题】:Django renders a template that does not exist in specified directoryDjango 渲染指定目录中不存在的模板
【发布时间】:2021-04-22 15:40:14
【问题描述】:

我有模型“视频”并且我有这个模型的列表视图,然后在另一个应用程序中我试图创建一个专用用户可以查看的视图“UserVideosListView”。当我在为此视图制作任何模板之前在浏览器中打开页面时,我可以看到当前用户的视频(不是所有视频)。

# inside 'users' app
class UserVideosListView(ListView):
    model = Video
    template_name = "users/user_videos.html"
    context_object_name = 'videos'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['videos'] = Video.objects.filter(author=self.request.user)
        return context

# inside 'videos' app
class VideoListView(ListView):
    model = Video
    paginate_by = 25
    template_name = 'videos/video_list.html'
    context_object_name = 'videos'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['videos'] = Video.published_videos.all()
        return context

附:我确定我输入的 URL 是最新的,并且“用户”目录中没有模板

【问题讨论】:

    标签: python python-3.x django django-3.1


    【解决方案1】:

    Django 渲染 videos/video_list.html 因为ListView 基于MultipleObjectTemplateResponseMixinBaseListView

    class ListView(MultipleObjectTemplateResponseMixin, BaseListView):
        """
        Render some list of objects, set by `self.model` or `self.queryset`.
        `self.queryset` can actually be any iterable of items, not just a queryset.
        """
    

    MultipleObjectTemplateResponseMixinGitHub)内,模板名也是根据model生成的。

    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    

    Django docsMultipleObjectTemplateResponseMixin

    模板名称后缀

    附加到自动生成的候选模板名称的后缀。默认后缀为 _list

    get_template_names()

    返回候选模板名称列表。返回以下列表:

    • 视图上 template_name 的值(如果提供)
    • /.html

    我建议你重写 get_queryset() 方法而不是 get_context_data()

    class UserVideosListView(ListView):
        model = Video
        context_object_name = 'videos'
        ...
    
        def get_queryset(self):
            return super().get_queryset().filter(author=self.request.user))
    

    【讨论】:

    • 我们不使用'template_name'来忽略这个吗?
    • @KuroshGhanizadeh,是的,没错,但模板应该存在(找到)。
    • @KuroshGhanizadeh,你想做什么?
    • 创建一个页面供用户在仪表板中查看他们的视频
    • 谢谢。你是对的。那是因为它在那个目录中没有找到任何东西
    猜你喜欢
    • 2016-06-07
    • 2014-03-10
    • 1970-01-01
    • 2022-07-22
    • 2016-07-10
    • 2014-04-11
    • 2018-05-20
    • 2018-11-05
    • 2019-04-20
    相关资源
    最近更新 更多