Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为两个不同的模板使用ListView类_Python_Django_Templates - Fatal编程技术网

Python 如何为两个不同的模板使用ListView类

Python 如何为两个不同的模板使用ListView类,python,django,templates,Python,Django,Templates,我在view.py中有一个ListView类 我使用这个视图来显示index.html中的文章列表。但是,我想在文章之后显示article.html中相同的文章列表。我已经正确使用了块,但是,它不会显示任何文章,因为在ListView中模板名称为index.html。如何解决此问题?在url.py中,您可以将模板名称设置为ListView url条目路由器的属性 url.py 在views.py中,甚至不需要设置模板 views.py 使用Mixin: class LatestArticleMi

我在view.py中有一个ListView类

我使用这个视图来显示index.html中的文章列表。但是,我想在文章之后显示article.html中相同的文章列表。我已经正确使用了块,但是,它不会显示任何文章,因为在ListView中模板名称为index.html。如何解决此问题?

在url.py中,您可以将模板名称设置为ListView url条目路由器的属性

url.py

在views.py中,甚至不需要设置模板

views.py

使用Mixin:

class LatestArticleMixin(object):

    def get_context_data(self, **kwargs):
        context = super(LatestArticleMixin, self).get_context_data(**kwargs)
        try:
            context['latest_article_list'] = Entertainmentblog.objects.order_by('-posted')[:25]
        except:
            pass
        return context
然后重构您的DetailView:

class DetailView(LatestArticleMixin, generic.DetailView):
    model = Entertainmentblog
    template_name = 'entertainment/article.html'
如果有文章,请在模板中:

{% if latest_article_list %}
    ....

{% endif %}

在本例中,您可以在url路由器中添加额外的上下文模板名称,并在CBV中为交换机工作。这里有更多信息,但是,article.html已经有一个视图DetailView。我如何更改它以包含ListView中的文章列表好的,我知道了,谢谢!
class LatestArticleMixin(object):

    def get_context_data(self, **kwargs):
        context = super(LatestArticleMixin, self).get_context_data(**kwargs)
        try:
            context['latest_article_list'] = Entertainmentblog.objects.order_by('-posted')[:25]
        except:
            pass
        return context
class DetailView(LatestArticleMixin, generic.DetailView):
    model = Entertainmentblog
    template_name = 'entertainment/article.html'
{% if latest_article_list %}
    ....

{% endif %}