views:

110

answers:

2

I just started using django for development. At the moment, I have the following issue: I have to write a page template able to represent different categories of data. For example, suppose I have a medical record of a patient. The represented information about this patient are, for example:

  1. name, surname and similar data
  2. data about current treatments
  3. ..and beyond: specific data about any other analysis (eg. TAC, NMR, heart, blood, whatever)

Suppose that for each entry at point 3, I need to present a specific section. The template for this page would probably look like a long series of if statements, one for each data entry, which will be used only if that information is present. This would result in a very long template.

One possible solution is to use the include directive in the template, and then fragment the main template so that instead of a list of if's i have a list of includes, one for each if.

Just out of curiosity, I was wondering if someone know an alternative strategy for this kind of pattern, either at the template level or at the view level.

+2  A: 

See this example: http://www.djangosnippets.org/snippets/1057/

Essentially, you can loop through a model's fields in the template.

I assume you just want to display the data present in all of these different fields correct? Looping through each field should provide you with the results you're looking for.

Alternatively, you can set up what you want to display in the view by adding your conditionals there. It will make your view functions messier but will clean up the template. The view also makes it easier to test for the existence of certain sections.

AlbertoPL
I liked the second proposal. Indeed I could arrange proper logic in the view (where I have full OO capability), and make a very generic template rendering the data.
Stefano Borini
+1  A: 

The answer to this depends a lot on how you've structured your data, which you don't say - are the extra bits of information in separate related tables, subclassed models, individual fields on the same model...?

In general, this sounds like a job for a template tag. I would probably write a custom tag that took your parent object as a parameter, and inspected the data to determine what to output. Each choice could potentially be rendered by a different sub-template, called by the tag itself.

Daniel Roseman