如何在模板中显示django表单向导的extra_context?

3 投票
2 回答
2959 浏览
提问于 2025-04-17 06:20

编辑:顺便说一下,我正在使用django 1.3

我有...

class CreateProductWizard(FormWizard):
    def get_template(self, step):
        if step == 1:
            return 'product/form_wizard/editor.html'
        else:
            return 'product/form_wizard/wizard_%s.html' % step
    def process_step(self, request, form, step):
        if step == 1:
            self.extra_context = {'ptype': form.cleaned_data}
            return
        else:
            return
    def done(self, request, form_list):
        # now that it's all together, store it.
        return render_to_response('product/form_wizard/done.html',
            {'form_data': [form.cleaned_data for form in form_list]},
            context_instance=RequestContext(request))

我想把self.extra_context传递到模板里。

我该怎么把它放到模板里呢?

我在模板里试过:

{{extra_context}}
{{form.extra_context}}
{{form.extra_context.ptype}}

等等...

2 个回答

5

根据文档,我觉得get_context_data就是你需要的东西:

这个方法会返回某一步的模板上下文。你可以重写这个方法,来为所有步骤或某些步骤添加更多的数据。这个方法返回一个字典,里面包含了渲染后的表单步骤。

3

最后我在模板中使用的是:

{{ptype}}

这个我之前已经试过了。

问题是,我现在还是不太明白为什么我有:

def process_step(self, request, form, step):
        if step == 1:
            self.extra_context = {'ptype': form.cleaned_data}
            return
        else:
            return

而有效的代码是:

def process_step(self, request, form, step):
        self.extra_context = {'ptype': 'hello!!',}

出于某种原因,传递给 'process_step()' 的 'step' 总是等于 0,这导致我的 'if step == 1:' 逻辑失败了……

在查看源代码(django.contrib.formtools.wizard.FormWizard)后,我发现可能出问题的地方是我的表单不合法。表单必须合法,步骤编号才能增加并调用 process_step 函数。不过,{{step}} 变量得到了正确的值。而且我对表单没有做什么奇怪的操作……

真奇怪。不过我主要的问题解决了。

撰写回答