Django - 在用户创建时创建用户配置文件

标签 django django-registration user-profile

我正在关注 Django 文档 here为了实现一个简单的目标:创建新用户后立即创建用户配置文件。

我有一个“帐户”应用程序,我的 accounts.models 如下所示:

# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from main.models import Store

class UserProfile(models.Model):

    GENRE_CHOICES = (
        ('m', 'Masculino'),
        ('f', 'Feminino'),
    )
    MARITAL_STATUS_CHOICES = (
        ('s', 'Solteiro'),
        ('c', 'Casado'),
        ('d', 'Divorciado'),
        ('v', 'Viúvo'),
    )

    user = models.ForeignKey(User, unique=True)
    birth_date = models.DateField()
    genre = models.CharField(max_length=1, choices=GENRE_CHOICES)
    address = models.CharField(max_length=150)
    postal_code_4 = models.PositiveIntegerField()
    postal_code_3 = models.PositiveIntegerField()
    locatity = models.CharField(max_length=30)
    marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES)
    child_amount = models.PositiveSmallIntegerField()
    is_merchant = models.BooleanField(default=False)
    store = models.ForeignKey(Store, null=True)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

对我来说一切都很好,但是当我尝试添加一个新用户(使用 django admin)时,而不是拥有一个新创建的用户和用户配置文件,我收到以下错误:
/admin/auth/user/add/处的内部错误
当前事务被中止,命令被忽略直到事务块结束


这是回溯错误部分:
/djangoProjects/lwboanova/lwboanova/apps/accounts/models.py in create_user_profile

34: UserProfile.objects.create(user=instance)

这似乎是一个完整性错误,但我没有得到它的原因。

如果你们中的任何人能在这方面给我一些帮助,那就太好了。

最佳答案

你不应该使用:

user = models.ForeignKey(User, unique=True)

而是使用这个:
from django.conf import settings
..
user = models.OneToOneField(settings.AUTH_USER_MODEL)

关于Django - 在用户创建时创建用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11488974/

相关文章:

Django 管理错误 ValidationError : [u'ManagementForm data is missing or has been tampered with']

python - Recaptcha 不显示 Django1.5 中的 Django 注册

windows - 使用变量后 PowerShell 命令失败

android - 我有一个应用程序/网络应用程序,但我找不到构建它所需的答案

python - Django模型FloatField错误 'float'对象没有属性 'as_tuple'

python - 如何将 python 站点迁移到另一台机器?

python - 无法导入名称 View

python - 将 success_url 传递给激活

python - Django - 身份验证,使用电子邮件确认注册

vbscript - 如何在 %AppData% 中创建文件夹和子文件夹