且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有来自两个不同模型的字段的 Django 表单

更新时间:2022-12-10 20:41:25

此页面上的其他答案涉及舍弃模型表单的好处,并且可能需要复制您免费获得的某些功能.

The other answers on this page involve tossing away the benefits of model forms and possibly needing to duplicate some of the functionality you get for free.

真正的关键是要记住一个html表单!=一个django表单.您可以将多个表单包装在一个 html 表单标签中.

The real key is to remember that one html form != one django form. You can have multiple forms wrapped in a single html form tag.

因此您可以只创建两个模型表单并在您的模板中呈现它们.除非某些字段名称发生冲突,否则 Django 将确定哪些 POST 参数属于每个参数 - 在这种情况下,在实例化每个表单时为每个表单提供一个唯一的前缀.

So you can just create two model forms and render them both in your template. Django will handle working out which POST parameters belong to each unless some field names *** - in which case give each form a unique prefix when you instantiate it.

表格:

class CompanyForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Company

class AccountForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Account

查看:

if request.method == 'POST':

    company_form = CompanyForm(request.POST)
    account_form = AccountForm(request.POST)

    if company_form.is_valid() and account_form.is_valid():

        company_form.save()
        account_form.save()
        return HttpResponseRedirect('/success')        

    else:
        context = {
            'company_form': company_form,
            'account_form': account_form,
        }

else:
    context = {
        'company_form': CompanyForm(),
        'account_form': AccountForm(),
    }

return TemplateResponse(request, 'your_template.html', context)

模板:

<form action="." method="POST">
    {% csrf_token %}
    {{ company_form.as_p }}
    {{ account_form.as_p }}
    <button type="submit">
</form>