创建一个Django表单来保存两个模型 [英] Creating one Django Form to save two models
问题描述
我有常规的Django 用户
模型和一个 UserDetails
模型( OneToOneField
with
User
),它作为 User
模型的扩展名。 (我尝试了Django 1.5的功能,这是一个令人头疼的奇怪的文档,所以我坚持使用 OneToOneField
选项)
I have the regular Django User
model and a UserDetails
model (OneToOneField
with User
), which serves as an extension to the User
model. (I tried Django 1.5's feature and it was a headache with strangely horrible documentation, so I stuck with the OneToOneField
option)
因此,在我建立一个自定义注册页面的过程中,该页面将包含由 User
字段和 UserDetails
字段,我想知道是否有一种方法可以自动生成表单(具有所有的验证)从这两个相关的模型中。我知道这适用于一个模型的形式:
So, in my quest to build a custom registration page that will have a registration form comprised of the User
fields and the UserDetails
fields, I wondered if there was a way to generate the form automatically (with all of its validations) out of these two related models. I know this works for a form made of one model:
class Meta:
model = MyModel
但是,无论如何,为包含两个相关模型的表单获得类似的功能?
But is there anyway to get a similar functionality for a form comprised of two related models?
推荐答案
from django.forms.models import model_to_dict, fields_for_model
class UserDetailsForm(ModelForm):
def __init__(self, instance=None, *args, **kwargs):
_fields = ('first_name', 'last_name', 'email',)
_initial = model_to_dict(instance.user, _fields) if instance is not None else {}
super(UserDetailsForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
self.fields.update(fields_for_model(User, _fields))
class Meta:
model = UserDetails
exclude = ('user',)
def save(self, *args, **kwargs):
u = self.instance.user
u.first_name = self.cleaned_data['first_name']
u.last_name = self.cleaned_data['last_name']
u.email = self.cleaned_data['email']
u.save()
profile = super(UserDetailsForm, self).save(*args,**kwargs)
return profile
这篇关于创建一个Django表单来保存两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!