如何在模板中避免逻辑?

时间:2016-08-02 07:46:26

标签: python django

我正在尝试开发一个论坛应用程序。

我试图在列表页面上显示每个类别中发布的最新主题。但是,我意识到添加了多个类别后,我需要为每个类别单独查询,或者它只是显示最新的主题。

我只是不确定如何在查看视图中保留我的逻辑。显然,我可以在for循环中执行查询,但这似乎不是MVT导向的。

这是我的views.py:

from django.shortcuts import render
from .models import ForumReply, ForumCategory, ForumTopic

def index(req):
    categories = ForumCategory.objects.all()

    #find latest topic or topic by reply
    topic = ForumTopic.objects.latest('created_at')
    reply = ForumReply.objects.latest('created_at')

    if (topic.created_at > reply.created_at):
        latest = topic
    else:
        latest = reply.topic

    return render(req, "forum/category_listing.html",
                  {'categories': categories, 'latest': latest})

我的category_listing.html:

{% extends '__base.html' %}
{% block content %}

    {% for category in categories %}
    <div class="forum_category">
        <h1><a href="{% url 'forum_topic_list' category.pk 1 %}">{{ category.title }}</a></h1>
        {{ category.body }}
        <br />
        <em>Latest Post: </em> {{ latest.title }} by {{ latest.user }} at {{ latest.created_at|date:"D d F Y h:i" }}
    </div>
    <br />
    {% endfor %}

{% endblock %}

1 个答案:

答案 0 :(得分:0)

您可以创建自定义模板标记,以返回每个类别的最新帖子。

这样的事情:

# views.py
def index(req):
    categories = ForumCategory.objects.all()
    return render(req, "forum/category_listing.html", {'categories': categories})

# templatetags/category_tags.py
@register.assignment_tag
def get_latest_post(category):
    # perform logic here for selecting latest post for specific category
    return latest


# category_listing.html
{% load category_tags %}
{% for category in categories %}
    {% get_latest_post category as latest %}
    <em>Latest Post: </em> {{ latest.title }} by {{ latest.user }} at {{ latest.created_at|date:"D d F Y h:i" }}
{% endfor %}

您可以阅读文档以获取更多信息https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#assignment-tags