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

Regarding this postI want to populate several HTML pages from a single Django view. The difference between this and the link I just mentioned is that I don't want it to be programmatically based. I have links to my template, such as "Reports" and other categories related to a particular company. If the user clicks the "Reports" link, I want to transfer them to a new page on which reports will be displayed. These data are interrelated, so it was originally assumed that I / should use the same view for all this. As I started writing this post, though, I began to wonder if I should actually use separate views for all pages. The amount should not exceed 3-4 pages, depending on how I want to divide the categories.

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

+4
source share
2 answers

A possible solution using class-based classes is to create a base view class that will collect general context data and then expand it as needed for specific data and a template. In fact, the base class should not be an extension View, the extension is ContextMixinenough

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

:

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

+3

, , , , . HTML. , .

0

All Articles