自定义模板Django Formwizard [英] Custom Templates Django Formwizard
问题描述
这对于某些人可能是显而易见的,但是我无法弄清楚如何超越get_template_name
来为我的form wizard
的不同步骤提供不同的模板.这是我到目前为止的内容:
This may be obvious to some, but I cannot figure out how to over-ride get_template_name
to provide a different template to the different steps of my form wizard
. Here is what I have so far:
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中:
I have read the Django docs and tried to use the method described there. In my 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'
.如何获得表单向导以为每个步骤显示不同的模板?
But this returns a KeyError at u'0'
. How can I get my form wizard to display different templates for each step?
推荐答案
django表单向导中的步骤为'0', '1', '2', ...
,因此您需要将TEMPLATES
字典更新为
The steps in django form wizard are as '0', '1', '2', ...
so you need to update your TEMPLATES
dict as
TEMPLATES = {"0": "myapp/step-one.html",
"1": "myapp/step-two.html",
"2": "myapp/step-three.html"}
然后按已完成的方式使用它get_template_names
:
And then use it get_template_names
as you have done:
class CreateWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
这篇关于自定义模板Django Formwizard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!