扩展用户模型

时间:2014-08-27 13:09:43

标签: python django

我想用自定义字段扩展User模型,但我有一点问题

我开始使用我想要的额外字段创建一个Profiles模型:

" models.py":

class Profiles(models.Model):
    user = models.OneToOneField(User)
    url = models.URLField()
    avatar = models.ImageField(upload_to='profile_avatar')

    def __str__(self):
        return self.user.username

然后,我创建了一个自定义的UserCreationForm,并使用原始用户模型中我想要的数据覆盖了save函数:

" forms.py":

class UserForm(UserCreationForm):
    first_name = forms.CharField()
    last_name = forms.CharField()
    email = forms.EmailField()
    url = forms.URLField()
    avatar = forms.ImageField()

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email",)

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=False)
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

最后,我创建了一个FormView来创建新用户并将额外数据保存在自定义Profiles模型中:

" views.py":

class SignIn(FormView):
    template_name = 'index/signin.html'
    form_class = UserForm
    success_url = reverse_lazy('signin')

    def form_valid(self, form):
        user = form.save()
        profile = Profiles()
        profile.user = user
        profile.url = form.cleaned_data['url']
        profile.avatar = form.cleaned_data['avatar']
        profile.save()
        return super(SignIn, self).form_valid(form)

我使用UserForm登录的第一个用户正确创建并且也创建了配置文件模型,但在第二次登录后,Django打印出此完整性错误:'(1062," Duplicate entry& #39;'用于密钥''")&#39 ;;正确创建用户,但没有配置文件

你知道我做得不好吗?

谢谢

0 个答案:

没有答案