簡體   English   中英

自定義模板Django Formwizard

[英]Custom Templates 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],})

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'返回KeyError at u'0' 如何讓表單向導為每個步驟顯示不同的模板?

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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM