Search code examples
djangosuper

Trouble with Django importing random list in base template using ´super´. What is the alternative to my work-around?


Update: Included a small adjustment thanks to replies, see below.

I'm trying to load an random list in the title of my webpage (base template). I was able to get this running using Super. However, at this point this is done for every view.

This seems illogical. As an amateur I have trouble finding out if this is true and/or if I am even right (I have some trouble interpreting the technical descriptions..).

Could someone push me in the right direction?

List generation:

def generatetraits():
    traits = ["trait1", "trait2", "trait3", "trait4", "trait5", "trait6",         
    "trait7", "trait8", "trait9", "trait10", "trait11"]
    random.shuffle(traits)
    traitlist = ""

    for i in range(0, 3):
        if (i == 0) or (i == 1):
            traitlist = traitlist + (traits[i] + " | ")
        else:
            traitlist = traitlist + (traits[i] + " ")

    return traitlist

SomeView example:

class SomeView(TemplateView):
    template_name = 'about.html'

    traitlist = generatetraits()

    def get_context_data(self, **kwargs):
        context = super(SomeView, self).get_context_data(**kwargs)
        context.update({'traits': self.traitlist})
        return context

Base template implementation:

<div class="title">
    <h1>Name</h1>
     <p> {{traits}} </p>
</div>

All pages/views are extended from the base. This makes it logical to me (as amateur;)) that it is just wrong to do this for every view.

Update:

Context call has been shortend to:

    def get_context_data(self, **kwargs):
        return {'traits': generatetraits()}

Solution

  • The solution was setting up a context processor as pointed out by @solarissmoke.

    This processor ended up as:

    def headertaggen(request):
        traits = ["trait1", "trait2", "trait3", "trait4", "trait5", "trait6"]
        random.shuffle(traits)
    
        return {'traits': ' | '.join(traits[:3:])}
    

    The key 'traits' is than called in the base template which is populated by all other templates.

    Thanks for the help everyone!