【问题标题】:Django, context dict not passing through to template? (for loop returns nothing)Django,上下文字典没有传递给模板? (for 循环不返回任何内容)
【发布时间】:2015-02-21 09:20:26
【问题描述】:

我搜索了这个,但找不到任何东西,所以在这里..

我的视图是这样设置的,status.html for 循环工作正常,但 tasks.html 根本没有注册我的 for 循环,比较 2 时我看不出我做错了什么查看函数/模板。

观看次数

from django.shortcuts import render
from todo.models import List, Item

# Create your views here.

def current_tasks(request):
    tasks = List.objects.all()
    tasks_dict = {'tasks': tasks}

    return render(request, 'tasks.html', tasks_dict)

def status_report(request):
    todo_listing = []

    for todo_list in List.objects.all():
        todo_dict = {}

        todo_dict['list_object'] = todo_list
        todo_dict['item_count'] = todo_list.item_set.count()
        todo_dict['items_complete'] = todo_list.item_set.filter(completed=True).count()
        todo_dict['percent_complete'] = int(float(todo_dict['items_complete']) / todo_dict['item_count'] * 100)

        todo_listing.append(todo_dict)

    return render(request, 'status.html', {'todo_listing': todo_listing})

tasks.html

    {% extends 'base.html' %}

    {% block content %}
    {% for tasks in tasks_dict %}
        <ul><li>{{tasks.title}}</li><
        <li>{{tasks.created_date}}</li>
        <li>{{tasks.priority}}</li>
        <li>{{tasks.completed}}</li></ul>
    {% endfor %}
    {% endblock %}

status.html

{% extends 'base.html' %}

{% block content %}
    <h1>Task List Status Report</h1>
{% for list_dict in todo_listing %}
    <h2>{{ list_dict.list_object.title }}</h2>

    <ul>
        <li>Number of items: {{ list_dict.item_count }}</li>
        <li>Number completed: {{ list_dict.items_complete }} ({{ list_dict.percent_complete }}%)</li>
    </ul>
{% endfor %}
{% endblock %}

</html>

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    您不会将任何名为 tasks_dict 的内容发送到您的模板;这只是您的上下文字典的本地名称。您发送到包含任务的模板的内容仅称为 tasks

    【讨论】:

    • 谢谢丹尼尔,我知道这是一个愚蠢的问题,但我没有意识到我没有将字典传递给模板。
    猜你喜欢
    • 2018-09-10
    • 2018-05-28
    • 2015-04-19
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多