【问题标题】:Custom Templates Django Formwizard自定义模板 Django Formwizard
【发布时间】:2013-09-29 03:03:51
【问题描述】:

这对某些人来说可能很明显,但我不知道如何覆盖get_template_name 以为我的form wizard 的不同步骤提供不同的模板。这是我到目前为止所拥有的:

class StepOneForm(forms.Form):
    color = forms.ChoiceField(choices=COLOR_CHOICES) 
    ...

class StepTwoForm(forms.Form):
    main_image = forms.ImageField()
    ...

class StepThreeForm(forms.Form):
    condition = forms.ChoiceField(choices=CONDITION)
    ...

class CreateWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
        id = form_list[0].cleaned_data['id']
        try:
            thing = Thing.objects.get(pk=id)
            instance = thing
        except:
            thing = None
            instance = None
        if thing and thing.user != self.request.user:
            raise HttpResponseForbidden()
        if not thing:
            instance = Thing()
            for form in form_list:
                for field, value in form.cleaned_data.iteritems():
                    setattr(instance, field, value)
            instance.user = self.request.user
            instance.save()
        return render_to_response('wizard-done.html', {
                'form_data': [form.cleaned_data for form in form_list],})

urls.py:

url(r'^create/$', login_required(CreateWizard.as_view([StepOneForm, StepTwoForm, StepThreeForm])), name='create_thing'),

我已阅读 Django 文档并尝试使用其中描述的方法。在我的 forms.py 中:

FORMS = [("step_one", myapp.forms.StepOneForm),
         ("step_two", myapp.forms.StepTwoForm),
         ("step_three", myapp.forms.StepThreeForm)]

TEMPLATES = {"step_one": "myapp/step-one.html",
             "step_two": "myapp/step-two.html",
             "step_three": "myapp/step-three.html"}

class CreateWizard(SessionWizardView):
    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]
        ...etc. ...

但这会返回一个KeyError at u'0'。如何让表单向导为每个步骤显示不同的模板?

【问题讨论】:

    标签: python django forms templates django-formwizard


    【解决方案1】:

    django 表单向导中的步骤为'0', '1', '2', ...,因此您需要将TEMPLATES dict 更新为

    TEMPLATES = {"0": "myapp/step-one.html",
                 "1": "myapp/step-two.html",
                 "2": "myapp/step-three.html"}
    

    然后像你一样使用它get_template_names

    class CreateWizard(SessionWizardView):
        def get_template_names(self):
            return [TEMPLATES[self.steps.current]]
    

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 2015-11-06
      • 2017-02-20
      • 2012-03-05
      • 1970-01-01
      • 2019-04-03
      • 2018-09-07
      • 2015-12-01
      • 2017-05-02
      相关资源
      最近更新 更多