我正在尝试使用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>]>
我在做什么错?
答案 0 :(得分:0)
解决方案:
我已经尝试过基于类的视图,并且可以正常工作。 带有列表视图 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循环非常完美。 不要犹豫,提出更好的解决方案。