Listing Active Portfolios, Projects, and Students - Sloathking/Foolish-Wizardz GitHub Wiki

Author: Ryan Montgomery

Listing Active Portfolios

To list active portfolios, the following lines may be used in the index function in views.py: image

What this is doing is

  1. Getting all student objects whose associated portfolio object that is active
  2. Printing "active portfolio query set" followed by the QuerySet which is a list of all the acquired student objects
  3. Rendering the index.html page and passing the QuerySet as an object called student_active_portfolios which can be referenced in the HTML file with Django syntax

In the template, listing the students will now be simple as creating a for-each loop, as in the below code snippet: image

Basically, Django is iterating through student_active_portfolios and printing the necessary information from each portfolio.

Listing Projects

It made sense to list projects on the portfolio-detail page. To do this, the projects associated with the portfolio must be added to the context in the PortfolioDetailView class, which by default will only get information from the Portfolio model. The get_context_data method can be used to do this as follows: image

The second line of the method is doing some kind of magic that gets only Project objects that are associated with the currently viewed Portfolio. This is incredibly convenient because it prevents having to get every Project in the database and filter through them by portfolio_id. As such, the methodology to list the projects in portfolio_detail.html is remarkably similar to that used to list each active portfolio. But, since a Portfolio can exist while not containing a single Project, it is recommended to add an if/else clause that checks if there are any projects before attempting to list them.

Please note that when additional methods are added to a generic DetailView, the template_name field **must **be set manually, as above. Otherwise, the template will not be found!

Listing Students

Listing students follows the same methodology, but is simpler to implement. The StudentListView class requires a whopping two lines of code, as below:

image

You will also need to add a line like this to urls.py, which tells Django to pass the StudentListView as a view: image

In the template simply iterate through the student objects with a for loop (this is demonstrated in the "Listing Portfolios" section), and you're done.