python - 计算数据库中的记录数: Django

标签 python html django

我正在尝试在 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/

相关文章:

javascript - 将 Django 模板转换为 pdf

python - 启动anaconda后,“pythonw.exe停止工作”崩溃错误

javascript - 在 Javascript 中提醒用户更新已成功

python - 使用django上传文件

jquery - 访问 html 5 相机闪光灯

php - html代码中的printf

javascript - jQuery tablesorter 排序格式化货币

python - 一旦遇到异常,我可以忽略下面的所有行并转到 for 循环中的另一个项目吗?

python - Numpy - 将第一行作为名称立即加载到结构化数组中?

python - 如何仅重试函数中产生错误的行