Django 在其他模板中传递 render_to_response 模板

Django pass render_to_response template in other template

这可能是绝对初学者的问题,因为我对编程还很陌生。我已经搜索了几个小时来寻找合适的解决方案,但我不知道还能做什么。

以下问题。我想要一个显示的视图。例如我数据库中的 5 个最新条目和 5 个最新条目(仅作为示例)

#views.py
import core.models as coremodels

class LandingView(TemplateView):
    template_name = "base/index.html"

    def index_filtered(request):
        last_ones = coremodels.Startup.objects.all().order_by('-id')[:5]
        first_ones = coremodels.Startup.objects.all().order_by('id')[:5]
        return render_to_response("base/index.html", 
        {'last_ones': last_ones,   'first_ones' : first_ones})  

Index.html显示HTML内容但不显示循环内容

#index.html

<div class="col-md-6">
    <p> Chosen Items negative:</p>
    {% for startup in last_ones %}
        <li><p>{{ startup.title }}</p></li>
    {% endfor %}
</div>

<div class="col-md-6">
    <p> Chosen Items positive:</p>
    {% for startup in first_ones %}
       <li><p>{{ startup.title }}</p></li>
    {% endfor %}

这是我的问题:

如何让for循环渲染具体内容?

我认为 Django show render_to_response in template 非常接近我的问题,但我没有看到有效的解决方案。

感谢您的帮助。

克里斯

-- 我根据此线程中提供的解决方案编辑了我的代码和问题描述

调用 render_to_response("base/showlatest.html"... 呈现 base/showlatest.html,而不是 index.html

负责呈现 index.html 的视图应将所有数据(last_onesfirst_ones)传递给它。

将模板包含到 index.html

{% include /base/showlatest.html %}

更改上面的视图(或创建一个新视图或修改现有视图,相应地更改 urls.py)以将数据传递给它

return render_to_response("index.html", 
{'last_ones': last_ones,   'first_ones' : first_ones})

概念是视图渲染某个模板(index.html),成为返回给客户端浏览器的html页面。 那个是应该接收特定上下文(数据)的模板,以便它可以包含其他可重用的部分(例如 showlatest.html)并正确呈现它们。

include 命令只是将指定模板 (showlatest.html) 的内容复制到当前模板 (index.html) 中,就好像它是输入的和其中的一部分一样。

因此您需要在负责呈现包含 showlatest.html 的模板的每个视图中调用 render_to_response 并将您的数据(last_onesfirst_ones)传递给它

抱歉,措辞扭曲,有些事情做起来容易解释起来难。 :)

更新

您上次的编辑说明您使用的是 CBV(Class 基于视图)。

那么你的观点应该是这样的:

class LandingView(TemplateView):
    template_name = "base/index.html"

    def get_context_data(self, **kwargs):
        context = super(LandingView, self).get_context_data(**kwargs)
        context['last_ones'] = coremodels.Startup.objects.all().order_by('-id')[:5]
        context['first_ones'] = coremodels.Startup.objects.all().order_by('id')[:5]
        return context

注意:我个人会避免依赖数据库设置的 id 来排序记录。

相反,如果您可以更改模型,请添加一个字段以标记模型的创建时间。例如

class Startup(models.Model):
    ...
    created_on = models.DateTimeField(auto_now_add=True, editable=False)

那么在您看来查询可以变成

    def get_context_data(self, **kwargs):
        context = super(LandingView, self).get_context_data(**kwargs)
        qs = coremodels.Startup.objects.all().order_by('created_on')
        context['first_ones'] = qs[:5]
        context['last_ones'] = qs[-5:]
        return context