我已将变量添加到Django视图中,并且尝试在模板上调用它们。我已经研究了几个相关的问题,并且我知道我需要添加一个上下文,我相信我已经做到了。
我对Tick
的使用感到有些困惑,使用通用视图时是否需要这样做?
这是我的观点的一个例子:
render()
在模板中添加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
或{{ first }}
不会产生任何结果,我缺少什么?
答案 0 :(得分:1)
通用视图中的上下文由get_context_data
生成。
您的情况应该是
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
除非您要更改默认行为,否则无需在通用视图中调用或修改render
。