在Django中使用多个表单

时间:2013-04-07 17:58:29

标签: django django-models django-forms

我有几个模型 - NodeLinkMap。地图包含link_idnode_a_idnode_b_id字段。我正在为Link显示一个表单,为Node显示2个表单。如何将输入的信息保存在Map模型中,该模型将存储关系?

1 个答案:

答案 0 :(得分:0)

我假设您正在使用ModelForms,并且地图需要保存链接和节点。

首先,您需要保存此模型,然后保存地图模型。我还假设,link_id,node_a_id和node_b_id被定义为models.ForeignKey(Link)......

所以看起来像这样:

# somehwere on your views.py ...

def my_display_forms_view(request):
    if request.method == 'POST':
        na = Node()
        nb = Node()
        link = Link()
        na_form = NodeForm(request.POST, instance=na)
        nb_form = NodeForm(request.POST, instance=nb)
        link_form = LinkForm(request.POST, instance=link)

        if na_form.is_valid() and nb_form.is_valid() and link_form.is_valid():
            na = na_form.save()
            nb = nb_form.save()
            link = link_form.save()
            map = Map(link_id=link, node_a_id=na, node_b_id=nb)
            # maybe here fill more fields for map
            map.save()
            # eventually do some more stuff
    else:
       ... generate new unbound forms here
    return render_to_response(...)