2

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

跟随问题。我想要一个显示的视图。例如,我的数据库中的 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非常接近我的问题,但我没有看到有效的解决方案。

谢谢您的帮助。

克里斯

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

4

1 回答 1

1

调用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,就好像它是输入的一样。

因此,您需要在负责呈现模板的每个视图中调用render_to_response并传递您的数据(last_ones和),该模板包括first_onesshowlatest.html

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

更新

您的最后一次编辑澄清了您正在使用 CBV(基于类的视图)。

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

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
于 2015-08-03T14:53:49.773 回答