【问题标题】:Python 3.6//Django 2.1.4//templates: for loop not working on usersPython 3.6//Django 2.1.4//模板:for 循环对用户不起作用
【发布时间】:2018-12-09 23:12:44
【问题描述】:

我正在尝试使用 for 循环将我的数据库中的所有用户显示到 html 上,但它什么也不返回:

这是我在 views.py 中的主视图:

def home(request):
    users = User.objects.all()
    return render( request, 'home.html', { 'users': users } )

这是我的 home.html 模板:

{% extends 'base_test.html' %} 


{% block content %}

{{user.username}} <!-- returns user1 because he is logged in -->

{% for user in users %} <!-- not working -->
  <p>{{user.username}}</p>
{% endfor %}

{% endblock content %}

来自python3 manage.py shell 的User.objects.all() 返回:

<QuerySet [<User: user1>, <User: user2>]>

我做错了什么?

【问题讨论】:

    标签: python-3.x django-templates


    【解决方案1】:

    解决方案:

    我尝试了基于类的视图并且它有效。 带有列表视图 views.py

    from django.generic.views import ListView
    class Home(ListView):
        template_name = 'home.html'
        queryset = User.objects.all()
    

    urls.py(这种方式调用基于类的视图)

    urlspatterns = [
        path('', Home.as_view(), name='home')
    ]
    

    home.html

    {% extends 'base_test.html' %} 
    {% block content %}
    
    <!-- i read that the class based view automatically creates variables in the shade for you to use. -->
    {% for user in user_list %}
    
         <!-- added another variable to check if it is effective -->  
        <p>{{user.username}}: {{user.email}}</p> 
    
    {% endfor %}
    {% endblock content %}
    

    并且遍历用户的 for 循环运行良好。 不要犹豫,提出更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2022-07-25
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      相关资源
      最近更新 更多