Ben P
Ben P

Reputation: 3379

Variables not displaying on Django template

I have added variables to my Django views and I am trying to call them on my template. I have researched several related questions and I understand that I needed to add a context, which I believe I have done.

I am slightly confused by the use of render(), is this required when using generic views?

Here is an example of my view:

class SubgenView(generic.TemplateView):
    template_name = 'projects/subgen.html'
    context_object_name = 'subject_line_gen'
    all = {
    "first": ['Save up','New in','Huge savings',],
    "cat": ['trainers','suits','onesies'],
    "brand": ['one', 'two', 'three'],
    "third": ['at crazy prices', 'in colours galore'],
    "end": ['click now!', 'come and get it!']
    }

    first = random.choice(all['first'])

    def create_subject_parts(self):
        first = random.choice(all['first'])
        test = 'hi'
        return first

Adding {{ first }} or {{ test }} to my template yields nothing, what am I missing?

Upvotes: 0

Views: 34

Answers (1)

4140tm
4140tm

Reputation: 2088

Context in generic views is generated by get_context_data.

In your case it would be

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["first"] = ['Save up','New in','Huge savings',]
    context["cat"] = ['trainers','suits','onesies']
    context["brand"] = ['one', 'two', 'three']
    context["third"] = ['at crazy prices', 'in colours galore']
    context["end"] = ['click now!', 'come and get it!']
    return context

There is no need to call or modify render in generic views, unless you are changing default behavior.

Docs

Upvotes: 1

Related Questions