同一网页上表单和表单集之间的关系

时间:2011-09-29 18:49:32

标签: python django forms foreign-key-relationship formset

我正在尝试将在formset中创建的所有对象与在与formset相同的网页上创建的对象相关联。所以,代码的一个例子就是:

def create_b(request):
    SpeciesFormSet = modelformset_factory(Species, fields=('common', 'scientific'))
    if request.method == 'POST':
        formset = SpeciesFormSet(request.POST)
        form1 = BForm(request.POST)
        if form1.is_valid():
            objcreate = BModel.objects.create(
                                name = form1.cleaned_data['name'],
                                ...
                                )
            objcreate.save()
            for forms in formset.forms:
                if forms.is_valid():
                    formset1 = Species.objects.create (
                                common = forms.cleaned_data['common'],
                                scientific = forms.cleaned_data['scientific'],
                                BName = form1.cleaned_data['name']
                                )
                    formset1.save()
                else:
                    formset = SpeciesFormSet()
                    form1 = BForm()
                    c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
                    c.update(csrf(request))
                    return render_to_response('Forms/create_b.html', c)
            return HttpResponseRedirect('/accounts/profile')
    else:
        formset = SpeciesFormSet()
        form1 = BForm()
    c = {'SpeciesFormSet' : SpeciesFormSet, 'form1' : form1}
    c.update(csrf(request))
    return render_to_response('Forms/create_b.html', c)

我遇到的问题是,当尝试将formset对象与表单对象关联时,它告诉我表单对象实际上并不存在。它在数据库中创建对象,但是没有任何formset对象。我收到错误“无法分配”u''“:”Species.BName“必须是”BModel“实例。”如果这有帮助。此外,关系是ForeignKey。反正有没有解决这个问题?谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

这个确切的模式是inline model formsets的用途。

答案 1 :(得分:0)

从错误中,看起来您正在分配属性应该是BModel的BName。或者,您想要使用BModel更改BName,或者您需要修复模型以使它们与物种的BName匹配。

formset1 = Species.objects.create (
    common = forms.cleaned_data['common'],
    scientific = forms.cleaned_data['scientific'],
    BName = form1.cleaned_data['name']
)
formset1.save()