Skip to content
Advertisement

django html template not loading from generic view from model

Introduction

I am currently working on a small piece of the project to understand more about the Django ORM and to display individual objects. Using Generic views to keep the code clean. (I am somewhat new to Django Framework)

Goal

The goal of this piece is to show how many users have written an article. For example, I have total of 4 articles. I need to show how many articles written by each user.

My console output:

User Article Count
testuser 2
testuser1 2
testuser2 0

my output on the HTML template:

User Article Count
testuser 0
testuser1 0
testuser2 0

Problem

I am not understanding why my console output is correct, but my HTML template isn’t showing the results. Please HELP me understand why it is doing this!!!!! If there is a similar post let me know! I have been looking everywhere for the answer, but I couldn’t find it on the internet.

Code

views.py

JavaScript

models.py

JavaScript

article_list.html

JavaScript

Hopefully is organized enough to understand the problem. Thanks in advance!!!

Advertisement

Answer

You are just rewriting the article_count variable in your for loop, so, the context gets assigned only to the last calculated value. You might create a dictionary something like {"user": {"object": user, "article_count": article_count}} for each user, and assign this dictionary to the context after making calculation for all of them, however, it is still not a clear way.

Best way would be to assign a related name for the connection:

JavaScript

And then, assign users to your context in the view:

JavaScript

In your template, you can now show the result like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement