Get total count of objects to display

Trying to get the total count of objects to display on the homepage.

Here’s my code

def dashboard(request):
    total_issues = Issue.objects.all().count()
    open_issues = Issue.objects.filter(mark_as=True).count()
    closed_issues = Issue.objects.filter(mark_as=False).count()

    context = {'total_issues': total_issues, 
               'open_issues': open_issues,
               'closed_issues': closed_issues}
    return render(request, 'issues/total_issues.html', context)

and my model

class Issue(models.Model):
    MARK_AS = ((True, 'Open'), (False, 'Closed'))
    
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True)
    mark_as = models.BooleanField(choices=MARK_AS, default=True)
    
    

    def __str__(self):
        return self.title


    def get_absolute_url(self):
        return reverse('issue-detail', kwargs={'pk': self.pk})

total_issues.html template

<br>

<div class="row">
	<div class="col">
		<div class="col-md">
			<div class="card text-center text-dark  mb-3" id="total_issues">
			  	<div class="card-header">
			  		<h5 class="card-title">Total Issues</h5>
			  	</div>
			  	<div class="card-body">
			    	<h3 class="card-title">{{total_issues}}</h3>
			  	</div>
			</div>
		</div>
	</div>

	<div class="col">
		<div class="col-md">
			<div class="card text-center text-dark  mb-3" id="open_issues">
			  	<div class="card-header">
			  		<h5 class="card-title">Open</h5>
			  	</div>
			  	<div class="card-body">
			    	<h3 class="card-title">{{open_issues}}</h3>
			  	</div>
			</div>
		</div>
	</div>

    <div class="col">
		<div class="col-md">
			<div class="card text-center text-dark  mb-3" id="closed_issues">
			  	<div class="card-header">
			  		<h5 class="card-title">Closed</h5>
			  	</div>
			  	<div class="card-body">
			    	<h3 class="card-title">{{closed_issues}}</h3>
			  	</div>
			</div>
		</div>
	</div>

</div>

home.html

{% extends "issues/base.html" %}
{% block content %}
{% include 'issues/total_issues.html' %}
    {% for issue in issues %}
      <article class="media content-section">
        <img class="rounded-circle article-img" src="{{ issue.author.profile.image.url }} " alt="">
        <div class="media-body">
          <div class="article-metadata">
            <a class="mr-2" href="{% url 'user-issues' issue.author.username %}">{{ issue.author }}</a>
            <small class="text-muted">{{ issue.date_posted }}</small>
            <small class="text-muted">{{ issue.mark_as|yesno:'Open, Closed'  }}</small>
          </div>
          <h2><a class="article-title" href="{% url 'issue-detail' issue.id %}">{{ issue.title }}</a></h2>
          
        </div>
      </article>
    {% endfor %}
    {% if is_paginated %}

      {% if page_obj.has_previous %}
        <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
      {% endif %}

      {% for num in page_obj.paginator.page_range %}
        {% if page_obj.number == num %}
          <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
          <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
        {% endif %}
      {% endfor %}

      {% if page_obj.has_next %}
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
        <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
      {% endif %}

    {% endif %}
{% endblock content %}

base.html (Only the main section)
This is where I tested to see if it was the total_issues.html template that was the problem by adding {{open_issues}} to the Sidebar, but it is empty as seen in the screenshot below

 <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% block content %}{% endblock %}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">{{open_issues}}</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>

And here are my views.py

def home(request):
    context = {
        'issues': Issue.objects.all()
    }
    return render(request, 'issues/home.html', context)

class UserAccesMixin(UserPassesTestMixin):
    def test_func(self):
        user = self.request.user
        return user.groups.filter(name='Manager').exists() or self.get_object().author == user

def dashboard(request):
    total_issues = Issue.objects.all().count()
    open_issues = Issue.objects.filter(mark_as=True).count()
    closed_issues = Issue.objects.filter(mark_as=False).count()

    context = {'total_issues': total_issues, 
               'open_issues': open_issues,
               'closed_issues': closed_issues}
    return render(request, 'issues/total_issues.html', context)

class IssueListView(ListView):
    model = Issue
    template_name = 'issues/home.html'
    context_object_name = 'issues'
    ordering = ['-date_posted']
    paginate_by = 5

class UserIssueListView(ListView):
    model = Issue
    template_name = 'issues/user_issues.html'
    context_object_name = 'issues'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Issue.objects.filter(author=user).order_by('-date_posted')
    

class IssueDetailView(DetailView):
    model = Issue


class IssueCreateView(LoginRequiredMixin, CreateView):
    model = Issue
    fields = ['title', 'content', 'mark_as', 'assignee']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class IssueUpdateView(LoginRequiredMixin, UserAccesMixin, UpdateView):
    model = Issue
    fields = ['title', 'content', 'mark_as', 'assignee']
    

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
    
class IssueDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Issue
    success_url = '/'

    def test_func(self):
        issue = self.get_object()
        if self.request.user == issue.author:
            return True
        return False


def about(request):
    return render(request, 'issues/about.html', {'title': 'About'})

The total issues do not get calculated and outputted

Where did I go wrong?

Please post your template.

Also, mark_as is a Boolean. Your filters should be comparing True or False, not Open or Closed.

I actually tried this first then switched it to what it is above. Both output are the same as you see above

You were right with it the first time then. We still need to see the template.

template has been edited in

1 Like

With all these css classes involved here, you don’t have something odd like trying to display white text on a white background, do you?

Visually inspect the rendered html in your browser to see what has been sent to the browser and rendered in the page.

Beyond that, are there other parts or conditions in your dashboard view that have been edited out?

Hm, I’ll try and see, thanks for pointing me in the right direction!

As for the dashboard view, no, I copied and pasted straight from my project

Even when I try to add {{closed_issues}} elsewhere, it still doesn’t output anything.

Where did you add it? Please post the modified template.

Even if the counts were 0, you should still see the 0 being rendered.

Actually, I’m surprised you get anything at all - if that’s your complete view, you have a syntax error in it. You should be getting a 500 from that view. Therefore, I must conclude that that is not the complete view. (You’ve got a reference to a variable named ordered_issues, but that variable isn’t defined in the view.)

You’re also not showing your corrected filters.

Finally, are you updating this through a JavaScript AJAX call? If so, please post that, too.

Alright this new edit is the current non-working state. I first thought that it was the
<div class="card text-center text-white mb-3" id="orders-delivered"
that was the issue because of the text-white, but then I changed it to text-dark, still no change.

Then I realized in that same line that id="orders-delivered" is wrong as well, so I’ve edited those to their respective id’s, but sadly no change as well.

And no I havent used AJAX anywhere in this project yet.

Could it be because I’m using class-based views instead of function-based that it’s not working?

Edit: I also added a new screenshot to show part of my homepage

That view (dashboard) is not a class-based view.

You’ve also posted two different templates without any apparent link between them.

I’ve still got the impression that there’s something you’re excluding from this description.

Sorry let me clarify, I’m using class-based views for all my CRUD features of the Issue model. I’ve added the views.py file to show this

I’ve also added another template view to show the connection between the total_issues.html and base.html. it is the home.html

But where are you calling the dashboard view to populate the template?