Пользовательские шаблоны Django Formwizard

Для некоторых это может быть очевидно, но я не могу понять, как переопределить 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],})

URL.py:

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

Я прочитал документы Django и попытался использовать описанный там метод. В моих формах.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'. Как заставить мастер форм отображать разные шаблоны для каждого шага?


person Nick B    schedule 24.09.2013    source источник


Ответы (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]]
person Rohan    schedule 24.09.2013