Django表单与两个不同的模型的字段 [英] Django form with fields from two different models
本文介绍了Django表单与两个不同的模型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要显示一个表单,其中有两个不同模型的多个字段。
表单只包含模型中的部分字段,布局将使用脆性表单。
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?
推荐答案
在您的forms.py
In your forms.py
from django import forms
class YourForm(forms.Form):
title = forms.CharField()
first_name = forms.CharField()
last_name = ...
在您的views.py
In your views.py
from forms import YourForm
from django import views
from models import Company, Account
class YourFormView(views.FormView)
template_name = 'some_template.html'
form_class = YourForm
success_url = '/thanks/'
def form_valid(self, form):
title = form.cleaned_data['title']
...
# do your processing here using Company and Account
# i.e. company = Company.objects.create(title=title, ...)
# account = Account.objects.get_or_create(
# user=..., company=company ...)
# ... more processing
#
# Call company.save() and account.save() after adding
# your processed details to the relevant instances
# and return a HttpResponseRedirect(self.success_url)
def is_valid(self):
# don't forget to validate your fields if need be here
像往常一样,文档很有帮助。
https://docs.djangoproject.com/en/1.7/topics/表单/
As usual the docs are pretty helpful. https://docs.djangoproject.com/en/1.7/topics/forms/
这篇关于Django表单与两个不同的模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文