如何在 Django 中使用 first_name、last_name 修改创建 UserProfile 表单? [英] How to create a UserProfile form in Django with first_name, last_name modifications?

查看:30
本文介绍了如何在 Django 中使用 first_name、last_name 修改创建 UserProfile 表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果认为我的问题很明显,并且几乎每个使用 UserProfile 的开发人员都应该能够回答.

If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it.

但是,我在 django 文档或 Django Book 中找不到任何帮助.

However, I could not find any help on the django documentation or in the Django Book.

当您想在 Django 表单中创建 UserProfile 表单时,您需要修改配置文件字段以及一些 User 字段.

When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as some User field.

但是没有forms.UserProfileForm(还有?)!

你是怎么做到的?

推荐答案

这是我最终做到的:

class UserProfileForm(forms.ModelForm):
    first_name = forms.CharField(label=_(u'Prénom'), max_length=30)
    last_name = forms.CharField(label=_(u'Nom'), max_length=30)

    def __init__(self, *args, **kw):
        super(UserProfileForm, self).__init__(*args, **kw)
        self.fields['first_name'].initial = self.instance.user.first_name
        self.fields['last_name'].initial = self.instance.user.last_name

        self.fields.keyOrder = [
            'first_name',
            'last_name',
            ...some_other...
            ]

    def save(self, *args, **kw):
        super(UserProfileForm, self).save(*args, **kw)
        self.instance.user.first_name = self.cleaned_data.get('first_name')
        self.instance.user.last_name = self.cleaned_data.get('last_name')
        self.instance.user.save()

    class Meta:
        model = UserProfile

这篇关于如何在 Django 中使用 first_name、last_name 修改创建 UserProfile 表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆