Django用户配置文件创建发生两次

时间:2013-02-24 20:30:08

标签: django django-admin signals

我看到Django用户个人资料创建时出现错误,但有几次问过,但其他问题和Django docs recommended修复的解决方案无效。

我在从Django管理页面创建新用户对象时尝试创建一个UserProfile模型。(请原谅我这里的语法,因为我使用堆栈溢出已经有一段时间了)

class UserProfile(models.Model):  
    user = models.OneToOneField(User)
    organization = models.IntegerField(null=True)
    phone = models.CharField(max_length=20, null=True, blank=True)
    phone_ext = models.CharField(max_length=8, null=True, blank=True)
    team_no = models.CharField(max_length=30, null=True, blank=True)    

post_save.connect(create_user_profile, sender=User, dispatch_uid="a.unique.string.that.does.not.help.me")

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

我已将用户个人资料添加到UserAdmin类,并取消注册/注册了管理站点条目。

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'



class UserAdmin(UserAdmin):
    inlines = (UserProfileInline, )
    actions = [set_organization]
    exclude = ('is_staff',)


try:
    admin.site.unregister(User)
    admin.site.unregister(RegistrationProfile)
    admin.site.unregister(Group)
## Re-register UserAdminadmin.site.unregister(User)
finally:
    admin.site.register(User, UserAdmin)
    admin.site.register(RegistrationProfile, RegistrationAdmin)
    admin.site.register(Group, GroupAdmin)

因此,每次尝试创建新用户时,我都会遇到user_profile_user_id字段的重复键错误。查看日志,在用户保存上运行了两个插入语句。第一个是缺少输入到管理界面中用户配置文件字段的所有数据。第二个包含所有数据但是失败,因为已经有初始插入只有他user_id。

我已经多次搜索过该项目,为UserProfile类重复导入了models.py,但没有找到任何内容。

有人有任何想法吗?

谢谢。

- 更新 -

Django版本是1.3

imports in the profile/models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_save
import logging

从admin.py导入 来自django.contrib import admin 来自django.contrib.auth.models导入组 从test.django.registration.models导入RegistrationProfile 从test.django.registration.admin导入RegistrationAdmin 从django.contrib.auth.admin导入UserAdmin,GroupAdmin 来自django.contrib.auth.models导入用户 从test.django.extranet.profile.models导入UserProfile 来自test.django.common.models.ajrsonline.ajrsonline_users import AjrsonlineUsers 来自test.django.common.middleware.ajrs_ldap import AJRSOnlineLdapBackend

1 个答案:

答案 0 :(得分:0)

使用if语句以限制第一个语句。像这样举例如:

 if instance.field_name:
     //save data here

     //In here you can save the value that has complete data