【问题标题】:Django: Templates for loop not looping through listDjango:循环模板不遍历列表
【发布时间】:2016-02-21 14:22:06
【问题描述】:

我不知道为什么,但是我的 Django 循环没有输出任何东西。这是相关代码。

我的 AbstractUser 类由这两个方法组成:

def get_followers(self):
    return [user for user in self.followers.all()]

def get_following(self):
    return [user for user in self.following.all()]

我的看法:

class UserFollowingView(View):
    def get(self, request, username):
        user = get_object_or_404(apps.get_model('users', 'User'), username=username)
        context = {
            'username': user.username,
            'following': user.get_following(),
        }
        return render(request, 'core/user_following.html', context)


class UserFollowersView(View):
    def get(self, request, username):
        user = get_object_or_404(apps.get_model('users', 'User'), username=username)
        context = {
            'username': user.username,
            'followers': user.get_followers(),
        }
        return render(request, 'core/user_followers.html', context)

我的模板:

user_following.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User | {{ username }}</title>
</head>
<body>
    <h1>{{ username }} | Following</h1><hr/>

    {% for user in user_following %}
        <h3>{{ user.username }}</h3>
    {% endfor %}
</body>
</html>

user_followers.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User | {{ username }}</title>
</head>
<body>
    <h1>{{ username }} | Followers</h1><hr/>

    {% for user in user_followers %}
        <h3>{{ user.username }}</h3>
    {% endfor %}
</body>
</html>

user_following.html 或 user_followers.html 文件都不起作用

我已确保每个用户都有关注者/关注者(因此填充了列表),但由于某种原因,循环没有运行。我没有收到任何错误。

>>> a = User.objects.get(username="Test")
>>> a.get_followers()
[<User: Test2>, <User: Test3>]
>>> 

查看输出:1

【问题讨论】:

  • 您的get_followersget_following 方法中不需要列表理解。您可以使用list(self.followers.all())list(self.following.all())
  • user_followinguser_followers 不在模板 context 中。

标签: python django django-templates


【解决方案1】:

您在模板中使用了user_followinguser_followers 作为独立变量;但它们不是,它们是用户的方法。但是,您已将 followingfollowers 变量传递到您的上下文中;也许您打算改用这些?

(请注意,这些方法都没有任何用处;它们完全等同于调用user.followers.all()user.following.all(),因此您最好在视图或模板中这样做。)

【讨论】:

  • 谢谢!我现在已经改变了!对不起,愚蠢的错误。
猜你喜欢
  • 2016-08-31
  • 2012-12-25
  • 2011-11-10
  • 2017-04-11
  • 2010-10-21
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多