1

为了向我的 auth.User 模型添加信息,我遵循了这篇文档。我想将用户链接到社会(例如假设用户是客户)以及该社会中的工作。所以这是我的代码:

社会/模型.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save


class UserProfile(models.Model):
    """
    Stores the user informations except
    login basic informations.
    """
    user = models.OneToOneField(User)
    firstname = models.CharField(max_length=128)
    lastname = models.CharField(max_length=128)
    society = models.ForeignKey('Society')
    job = models.ForeignKey('UserJob')


class Society(models.Model):
    """
    Stores the informations about the societies.
    """
    name = models.CharField(max_length=128)


class UserJob(models.Model):
    """
    Stores the user job category in the society.
    """
    name = models.CharField(max_length=64)


def create_user_profile(sender, instance, created, **kwargs):
    """
    Uses the post_save signal to link the User saving to
    the UserProfile saving.
    """
    if created:
        UserProfile.objects.create(user=instance)


#the instruction needed to use the post_save signal
post_save.connect(create_user_profile, sender=User)

社团/admin.py:

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from societies.models import UserProfile, Society, UserJob


class UserProfileInline(admin.StackedInline):
    """
    Defines an inline admin descriptor for UserProfile model
    which acts a bit like a singleton
    """
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'


class UserAdmin(UserAdmin):
    """
    Defines a new User admin.
    """
    inlines = (UserProfileInline, )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

admin.site.register(Society)
admin.site.register(UserJob)

我添加了 UserProfileInline 以便在我的管理站点用户表单中包含这些字段。我将此行添加到我的 settings.py 中:

AUTH_PROFILE_MODULE = 'societies.UserProfile'

那么问题是,当我尝试通过管理站点上的用户表单创建用户时,包括填写用户配置文件特定的字段,我得到了这个:

/admin/auth/user/add/ 处的 IntegrityError

(1048,“列 'society_id' 不能为空”)

因为我在表格上指定了一个社会,所以我问自己问题是否来自我的 create_user_profile 函数的信号处理。考虑到我之前提到的文档,没有什么可做的了。但是,我是否不必通过 UserProfile.create(...) 调用来精确填写 UserProfile 字段 firstname、lastname、society 和 job?(除了“user=instance”参数)。在这种情况下,我不知道如何获取正确的元素来填充参数。在文档中没有对“accepted_eula”和“favorite_animal”做任何事情,所以我当然错了......不是吗?

非常感谢您的任何回复。我为我的语言道歉。

4

1 回答 1

3

我发现我的错误,我不得不在 UserProfile 模型中的 Society 和 UserJob 外键字段中添加一个默认值。另一种解决方案是指定它们可以为空。

对这种缺乏关注感到抱歉。

于 2012-10-01T10:20:23.287 回答