Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving multiple templates from a single view (or should I use multiple views?)

Related to this post, I want to populate multiple HTML pages from a single Django view. The difference between this and the link I just mentioned is, I don't want it to be programmatically based. I have links on my template like "Reports" and other company-specific categories. If the user clicks on the Reports link, I want to take them to a new page that will show them the reports. This data is all interrelated, so I initially assumed I would/should be using the same view for all of it. As I started to write this post though, I started wondering if I should in fact use separate views for all of the pages. There shouldn't be more than 3-4 pages total, depending on how I want to split up the categories.

So TL;DR: Should I use separate views for each HTML page in my template, or should/could I use a single view to populate all of the various pages on the site, even if most of the data comes from the same sources?

like image 390
Tim S. Avatar asked Mar 10 '16 19:03

Tim S.


1 Answers

A possible solution using class based Views is to create a base view class that will collect the common context data and then extend it as necessary for the specific data and template. Actually the base class does not have to be an extension of View, a ContextMixinextension is sufficient

The base class should look like this:

class BaseContextMixin(ContextMixin):

    def get_context_data(self, **kwargs):
        context_data = super(BaseContextMixin, self).get_context_data(**kwargs)
        common_data_1 = ...
        context_data["common_key_1"] = common_data_1
        common_data_2 = ...
        context_data["common_key_2"] = common_data_2
        ...
        return context_data

the views then can be implemented as follows:

class MyFirstView(TemplateView, BaseContextMixin):
    template_name = "mir/my_first_template.html"

    def get_context_data(self, **kwargs):
        context_data = super(MyFirstView, self).get_context_data(**kwargs)
        context_data["my_special_key"] = my_special_data
        return context_data

class MySecondView(TemplateView, BaseContextMixin):
    template_name = "mir/my_second_template.html"

    def get_context_data(self, **kwargs):
        context_data = super(MySecondView, self).get_context_data(**kwargs)
        context_data["my_special_key_2"] = my_special_data_2
        return context_data

This way you avoid redundant code and at the same time you can keep the structure simple

like image 106
Daniele Bernardini Avatar answered Oct 17 '22 14:10

Daniele Bernardini