【问题标题】:PostList() received an invalid keyword 'template_name'PostList() 收到无效的关键字“template_name”
【发布时间】:2016-11-02 03:19:33
【问题描述】:

as_view 只接受已经是类属性的参数

这对我来说毫无意义,因为 template_name 是一个属性。我检查了类似的问题,但找不到代码哪里出错的迹象。这是我的代码。

urls.py:

from django.conf.urls import url
from .views import PostList

urlpatterns = [
    url(r'^$',
        PostList.as_view(
            template_name='blog/post_list.html'),
        name='blog_post_list'),
]

views.py

from django.views.generic import View
from .models import Post


class PostList(View):
    def get(self, request):
        return render(
            request,
            'blog/post_list.html',
            {'post_list': Post.objects.all()})

【问题讨论】:

  • 即使 PostList 确实接受了一个 template_name 参数,但您显然没有使用它,因为您直接在 get 中硬编码模板名称。
  • 谢谢。 Django 和 Python 对我来说是新的,但在你的帮助下,我能够立即应用解决方案。这正是我所需要的。

标签: django


【解决方案1】:

View 类没有template_name 属性,您要么想使用TemplateView,要么使用ListView 更有意义

class PostList(ListView):
    context_object_name = 'post_list'
    template_name = 'blog/post_list.html'
    def get_queryset(self):
        return Post.objects.all()

注意:无论哪种方式,由于您已经在视图中设置了模板名称,因此您实际上不需要将其包含在对 as_view 的调用中

【讨论】:

  • 由于 op 需要 Post.objects.all() 没有任何自定义,我们可以这样做:model = Post 而不是 get_queryset 方法
  • @VinayakKaniyarakkal - 我试图避免对 OP 的代码进行太多更改,因此它仍然有一些相似之处,但可以肯定的是,这也可以
猜你喜欢
  • 1970-01-01
  • 2020-05-03
  • 2012-09-23
  • 2019-09-03
  • 2020-07-13
  • 2015-07-15
  • 2020-04-12
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多