【问题标题】:Django data from context not showing in template来自上下文的 Django 数据未显示在模板中
【发布时间】:2021-04-21 05:35:24
【问题描述】:

我被 Django 中的模板上下文困住了。在我的模板中,我显示了有关球队的信息,并且我还想显示该球队的球员。在上下文中,我从团队中传递了球员,但是当我想显示这些数据时,它在模板中不起作用。我还尝试添加一些示例数据,例如"test":123,并将其显示在模板中,例如{{test}},但它也不起作用。 views.py*

def team_profile(request, name):
    team = Team.objects.get(name=name)
    player_list_filtered = []
    player_list = User.objects.all()
    for player in player_list:
        if player.profile.team.name == team.name:
            player_list.append(player)

    context = {
        'team': team,
        'players': player_list_filtered,
        'test': 123
    }

    return render(request, 'blog/team_profile.html', context)

team_profile.html*

{% block content %}
<div class="d-flex align-items-start flex-column content-section">
<img class="rounded-circle account-img" src="{{ team.image.url }}">
    <h1>{{team.name}}</h1>
    <h3>Mecze: {{team.matches}}</h3>
    <h3>League: {{team.league}}</h3>
    {% for player in players %}
        <h3>{{player.first_name}}</h3>
    {% endfor %}

    <p>Test: {{test}}</p>

</div>
{% endblock content %}

这是我的结果

【问题讨论】:

  • 你通过 player_list_filtered 但它是空的。我想你想在你的上下文中传递 player_list
  • 当我通过 player_list 时它也不起作用。看,即使我通过test 也不会显示
  • 在视图的循环中添加打印语句,以检查追加后列表是否仍然为空。像 print(player.first_name) 这样的东西取决于你有什么,这样你就可以准确地知道你的循环是否真的在工作

标签: python django templates django-templates


【解决方案1】:

将这个:player_list.append(player) 替换成这个:player_list_filtered .append(player) 那么你的列表应该存储有效的玩家。

【讨论】:

  • 问题不同,DetailView 中没有显示来自视图上下文的任何内容。我必须在我的详细视图类中覆盖 get_context_data。无论如何感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2015-03-01
  • 2020-03-03
相关资源
最近更新 更多