如何使用UserProfile中的字段扩展UserCreationForm [英] How to extend UserCreationForm with fields from UserProfile

查看:299
本文介绍了如何使用UserProfile中的字段扩展UserCreationForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个 post 关于如何使用额外的字段(如电子邮件)扩展UserCreationForm。但是,电子邮件字段已经在预先建立的用户模型中定义了。

I found this post on how to extend the UserCreationForm with extra fields such as "email." However, the email field is already defined in the pre-built user model.

我创建了一个额外的模型(称为UserProfile),它可以延续Django的预先构建的User类。如何使用UserProfile中定义的这些字段出现在我的UserCreationForm中?

I created an extra model (called UserProfile) that futher extends Django's pre-built User class. How do I get these fields I defined in UserProfile to appear in my UserCreationForm?

推荐答案

根据您的 UserProfile 模型(不幸的是,使用 ModelForm 避免重复自己并不容易),然后创建并保存新的code> UserProfile 实例在覆盖的 save()函数中。改编自您链接到的帖子:

Add fields as appropriate for your UserProfile model (it's not too easy to use a ModelForm to avoid Repeating Yourself, unfortunately), then create and save a new UserProfile instance in the over-ridden save() function. Adapted from the post you linked to:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


class UserCreateForm(UserCreationForm):
    job_title = forms.CharField(max_length=100, required=True)
    age = forms.IntegerField(required=True)

    class Meta:
        model = User

    def save(self, commit=True):
        if not commit:
            raise NotImplementedError("Can't create User and UserProfile without database save")
        user = super(UserCreateForm, self).save(commit=True)
        user_profile = UserProfile(user=user, job_title=self.cleaned_data['job_title'], 
            age=self.cleaned_data['age'])
        user_profile.save()
        return user, user_profile

这篇关于如何使用UserProfile中的字段扩展UserCreationForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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