我正在尝试在 Django 中输出数据库中“订阅者”数量的计数,我在 View 中找到了计数,然后我认为我在 html 中正确使用了它,但它总是只是输出“有订阅者”,但没有数字,当我在 html 中使用“|length”时,它总是输出 0,所以我不确定我的错误是什么。
views.py
def list_todo_items(request):
context = {'todo_list' : Todo.objects.all()}
count = Todo.objects.count()
context2 = {'count': count}
# context = {'count': Todo.objects.count()}
# count = Todo.objects.count()
return render(request, 'index.html',context,context2)
def insert_todo_item(request: HttpRequest):
todo = Todo(content=request.POST['content'])
try:
todo.full_clean()
except ValidationError:
# pymsgbox.alert('ValidationError! Phone number must be entered in the format: +999999999. Up to 15 digits allowed.', 'Title')
return redirect('/main/list/')
todo.save()
return redirect('/main/list/')
def delete_todo_item(request,todo_id):
todo_to_delete = Todo.objects.get(id=todo_id)
todo_to_delete.delete()
return redirect('/main/list/')
index.html
{% for todo in todo_list %}
<li class="list-group-item"> {{todo.content}}
<form action="{% url 'delete_todo_item' todo.id %}" method="post" class="float-right d-inline">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn">
<i class="far fa-trash-alt fa-lg text-danger float-right"></i>
</button>
</form>
</li>
<li class="list-group-item">
<span class="font-italic">There are {{ count }} subscribers.</span>
</li>
{% empty %}
<li class="list-group-item">
<span class="font-italic">No current subscribers.</span>
</li>
{% endfor %}
最佳答案
您可以将多个项目传递到相同上下文。字典允许添加多个键值对(只要键是可散列的且唯一的):
def list_todo_items(request):
context = {
<b>'todo_list'</b>: Todo.objects.all(),
<b>'count'</b>: Todo.objects.count()
}
return render(request, 'index.html', <b>context</b>)
关于python - 计算数据库中的记录数: Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61350232/