创建一个 Django 表单来保存两个模型 [英] Creating one Django Form to save two models
问题描述
我有常规的 Django User
模型和一个 UserDetails
模型(OneToOneField
和 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屋!