【问题标题】:How to bundle many forms in single instance in django如何在 django 的单个实例中捆绑多个表单
【发布时间】:2012-06-13 09:38:49
【问题描述】:

主要问题是是否有任何方法可以将许多 django 表单捆绑到单个实例中,以明确我需要解释我的问题:

我创建了一堆需要协同工作以显示单个视图的表单类。

    from_form = move_forms.WaypointForm(prefix="marker-from", instance=move.from_place)
    to_form = move_forms.WaypointForm(prefix="marker-to", instance=move.to_place)
    #Notice that last two form are of the same class 
    through = ThroughFormset(prefix="through", queryset=move.waypoints_db.all())
    path_form = move_forms.CarMovePathForm(path=move.path)
    date_form = move_forms.MoveForm(instance=move)

    #put all this into context instance and render

所有这些表单基本上都显示/编辑相同的数据库实例 --- 但通过应用程序以不同的配置重用(所以我不能只是手动创建将封装它的类)。

网页中有很多表单很麻烦,例如我必须编写这样的代码:

 if transportation_form.is_valid() and from_form.is_valid() and \
    to_form.is_valid() and through.is_valid() and path_form.is_valid():

我无法将干净的表单属性传递给视图,因为大多数 viev 都以这种方式使用多种表单。

是否有任何明智的方法来捆绑这些表单 --- 或者只是我的设计被破坏了(如果有,如何修复它)。

【问题讨论】:

    标签: django forms django-forms


    【解决方案1】:

    这个呢

    from_form = move_forms.WaypointForm(
        request.POST or None,
        prefix="marker-from",
        instance=move.from_place)
    # ... other forms declared the same way
    
    forms = {
        'from_form': from_form,
        'to_form':  to_form,
        # ...
    }
    if all(f.is_valid() for f in forms.values()):
        # ...
        return redirect('success')
    return render(request, 'template.html', {'forms': forms})
    

    【讨论】:

    • 好吧,我不喜欢传递字典(尤其是我想以某种方式启用将多表单作为视图参数传递)。我可能会酝酿一些MultipleForm 类,它会像你建议的那样做,但我还没有那么绝望——而且可能有一个现成的解决方案。尽管如此,这个解决方案肯定比只使用许多变量要好。
    • @jb。您如何想象“现成的解决方案”?一些捆绑四种形式和一个具有不同kwargs的formset的类?我不认为有人创造了这个。
    • 好吧,一些类允许我将表单列表传递给构造函数,并提供适用于所有表单的表单的方法和属性。喜欢错误:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多