创建一个Django表单来保存两个模型

编程入门 行业动态 更新时间:2024-10-24 21:34:17
本文介绍了创建一个Django表单来保存两个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有常规的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表单来保存两个模型

本文发布于:2023-11-30 11:01:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649737.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   创建一个   模型   两个   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!