2

I'm trying to output the count of the number of "subscribers" in my database in Django, I've found count in my view and then I think I'm using it correctly in the html, but it always just outputs "there are subscribers" without the number, when I use "|length" in the html it always outputs 0, so I'm not sure what my error is.

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 %}

1 Answer 1

3

You can pass multiple items to the same context. A dictionary allows to add multiple key-value pairs (as long as the keys are hashable, and unique):

def list_todo_items(request):
    context = {
        'todo_list': Todo.objects.all(),
        'count': Todo.objects.count()
    }
    return render(request, 'index.html', context)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.