如何使用 UserProfile 中的字段扩展 UserCreationForm [英] How to extend UserCreationForm with fields from UserProfile
问题描述
我发现了这个帖子 关于如何使用电子邮件"等额外字段扩展 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
来避免不幸的是,重复你自己),然后在覆盖的 save()
函数中创建并保存一个新的 UserProfile
实例.改编自您链接到的帖子:
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屋!