djangoで複数のフォームを作成するのに問題があります。私は2つのモデルを持っています、Space
そしてEntity
。各スペースには、それに関連するN個のエンティティを含めることができます。
2つのModelFormsを使用してフォームを作成し、「明らかに」機能するビューを作成しました。つまり、スペースフォームは保存されますが、エンティティフォームのデータは保存されません。フォームを保存すると、フォームが「部分的に」保存されることには意味がありません。
views.py
def all(items):
import operator
return reduce(operator.and_, [bool(item) for item in items])
def create_space(request):
"""
Create new space with its related entities. In this view the author
field is automatically filled.
"""
space_form = SpaceForm(request.POST or None, request.FILES or None)
entity_forms = [EntityForm(request.POST or None, prefix=str(x)) for x in range(0,3)]
if request.POST:
space_form_uncommited = space_form.save(commit=False)
space_form_uncommited.author = request.user
if space_form.is_valid() and all([ef.is_valid() for ef in
entity_forms]):
new_space = space_form_uncommited.save()
for ef in entity_forms:
ef_uncommited = ef.save(commit=False)
ef_uncommited.space = new_space
ef_uncommited.save()
# We add the created spaces to the user allowed spaces
space = get_object_or_404(Space, name=space_form_uncommited.name)
request.user.profile.spaces.add(space)
return redirect('/spaces/' + space.url)
return render_to_response('spaces/space_add.html',
{'form': space_form,
'entityform_0': entity_forms[0],
'entityform_1': entity_forms[1],
'entityform_2': entity_forms[2]},
context_instance=RequestContext(request))
forms.py
class SpaceForm(ModelForm):
"""
"""
class Meta:
model = Space
class EntityForm(ModelForm):
"""
"""
class Meta:
model = Entity
テンプレートコードが長すぎるため、ここに貼り付けます。