django 1.3 - 保存多个表单进行部分保存

发布于 2024-11-10 04:47:58 字数 2105 浏览 0 评论 0原文

我在 django 中制作多个表单时遇到一些麻烦。我有两个模型,SpaceEntity。每个空间可以有N个与其相关的实体。

我创建了一个包含两个 ModelForm 的表单,并编写了一个“显然”有效的视图。也就是说,它保存的是空间表单,而不是实体表单上的数据。我认为保存表单是对其进行“部分”存储,这对我来说没有意义。

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

模板代码粘贴在此处 因为太长了。

I'm having some troubles making multiple forms in django. I have two models, Space and Entity. Each space can have N entities related to it.

I've created a form with two ModelForms, and writed a view that works "apparently". This is, it saves the space form, but not the data on the entity form. I does not make sense to me that saving the forms does a "partial" storage of it.

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

The template code is pasted here because is too long.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煞人兵器 2024-11-17 04:47:58

您不需要创建对象,ModelForm 会为您完成此操作,因此请删除行 space = Space()entity = Entity() 并且不要传递任何实例到表单。

并且不要重新发明 all 函数,它已经是 Python 内置函数。 :-)

You don't need to create objects, ModelForm will do it for you, so remove lines space = Space() and entity = Entity() and don't pass any instance to forms.

And don't reinvent all function, it's already Python built-in. :-)

城歌 2024-11-17 04:47:58

已解决

使用 RAW 表单时出现某种问题。我将 EntityForm 转换为 ModelFormSet,之后实体被保存。

还修复了entity.space 声明,它存储了一个NoneObject

最终代码:

views.py

def create_space(request):

    space_form = SpaceForm(request.POST or None, request.FILES or None)
    entity_forms = EntityFormSet(request.POST or None, request.FILES or None,
                                 queryset=Entity.objects.none())

    if request.POST:
        space_form_uncommited = space_form.save(commit=False)
        space_form_uncommited.author = request.user

        if space_form.is_valid() and entity_forms.is_valid():
            new_space = space_form_uncommited.save()
            space = get_object_or_404(Space, name=space_form_uncommited.name)

            ef_uncommited = entity_forms.save(commit=False)
            for ef in ef_uncommited:
                ef.space = space
                ef.save()
            # We add the created spaces to the user allowed spaces

            request.user.profile.spaces.add(space)
            return redirect('/spaces/' + space.url)

    return render_to_response('spaces/space_add.html',
                              {'form': space_form,
                               'entityformset': entity_forms},
                              context_instance=RequestContext(request))

forms.py

from django.forms.models import modelformset_factory
EntityFormSet = modelformset_factory(Entity, extra=3)

SOLVED

There was some kind of problem using RAW forms. I converted EntityForm to a ModelFormSet and after that, the Entities got saved.

Fixed also the entity.space delaration, it was storing a NoneObject.

Final code:

views.py

def create_space(request):

    space_form = SpaceForm(request.POST or None, request.FILES or None)
    entity_forms = EntityFormSet(request.POST or None, request.FILES or None,
                                 queryset=Entity.objects.none())

    if request.POST:
        space_form_uncommited = space_form.save(commit=False)
        space_form_uncommited.author = request.user

        if space_form.is_valid() and entity_forms.is_valid():
            new_space = space_form_uncommited.save()
            space = get_object_or_404(Space, name=space_form_uncommited.name)

            ef_uncommited = entity_forms.save(commit=False)
            for ef in ef_uncommited:
                ef.space = space
                ef.save()
            # We add the created spaces to the user allowed spaces

            request.user.profile.spaces.add(space)
            return redirect('/spaces/' + space.url)

    return render_to_response('spaces/space_add.html',
                              {'form': space_form,
                               'entityformset': entity_forms},
                              context_instance=RequestContext(request))

forms.py

from django.forms.models import modelformset_factory
EntityFormSet = modelformset_factory(Entity, extra=3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文