带有来自两个不同模型的字段的 Django 表单 [英] Django form with fields from two different models
问题描述
我需要显示一个表单,其中包含来自 2 个不同模型的多个字段.表单将仅包含模型中的部分字段,并且将使用清晰的表单进行布局.
I need to display one form, with multiple fields from 2 different models. Form will contain only part of fields from models, and layout will be made using the crispy forms.
我的模型:
class Company(BaseModel):
title = models.CharField(_('Company'), max_length=128)
domain = models.CharField(_('Domain'), max_length=128)
class Account(BaseModel):
company = models.ForeignKey(Company)
user = models.OneToOneField(User)
role = models.CharField(_('Role'), choices=ROLES, default='member', max_length=32)
我想以表格形式显示的字段:公司名称、用户名、用户姓、用户邮箱
Fields which I want to show in form: company title, user first name, user last name, user email
有可能吗?我该怎么做?
Is it even possible? How can I do this?
推荐答案
此页面上的其他答案涉及舍弃模型表单的好处,并且可能需要复制您免费获得的某些功能.
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 clash - 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>
这篇关于带有来自两个不同模型的字段的 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!