是的,這是可能的,就像你建議最好的事情是使用嚮導表格。您可以使用盡可能多的型號自定義您的嚮導窗體。我會告訴你一個樣品方式2個步驟創建表單:
我想指出,在這種情況下,也許你可以考慮做出動態的第二步,以防父母可以有多個孩子。我強烈 recommedn你檢查這兩個文檔頁:
第一步:根據您的需要爲嚮導形式(如創建多種形式ms.py)
- 這形成您要創建可以爲你想要的形式
class NameForm01 (forms.ModelForm): class Meta: model = Parent fields = ['name', 'city']
名正常形式或ModelForms
更改 「NameForm01」 class NameForm02 (forms.ModelForm): class Meta: model = Child # We don't add the parent field because we relate the child # with the parent in the view fields = ['name' ]
第二步驟:創建嚮導視圖(views.py)
from django.contrib.formtools.wizard.views import SessionWizardView
class YourNameWizard(SessionWizardView):
instance = None
form_list = [NameForm01, NameForm02]
template_name = "your_wizard_base.html" # Template used to render the forms
def done(self, form_list, **kwargs):
# Parent Information is in form 0
parent_name = form_list[0].cleaned_data['name']
parent_city = form_list[0].cleaned_data['city']
# Now we create the Parent object to relate with child
new_parent = Parent(name=parent_name, city=parent_city)
new_parent.save()
# Child information is in form 1
child_name = form_list[1].cleaned_data['name']
# Now we create the Child object related with new_parent
new_child = Child(name=child_name, parent=new_parent)
return HttpResponseRedirect(reverse('your_return_url'))
第三步:創建鏈接到管理嚮導形式(網址。PY)
from YOUR_PROJECT.forms import NameForm01, NameForm02
from YOUR_PROJECT.views.content import YourNameWizard
# ... other imports you have in your urls.py ...
urlpatterns = patterns('',
# ... other patterns ...
url(r'^your/url/?$', YourNameWizard.as_view([NameForm01, NameForm02]), name='your_url_name'),
# ... other patterns ...
)
第四步:創建嚮導形式將使用
這個模板是文檔(here)
在此之後在Django提供了示例模板模板例如,您應該將此模板稱爲「your_wizard_base.html」,並將其放入模板文件夾
{% extends "base.html" %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
此示例模板可能足以讓您使用WizardForm進行練習,然後將其調整爲您的願望。