在Django Admin中添加/编辑内联外键字段的问题

时间:2011-07-15 15:43:16

标签: django django-admin user-profile

我有两个模型,School和UserProfiles,其中UserProfiles有一个ForeignKey to School。在Django Admin中,我希望能够选择一所学校并让它显示所有具有外键的用户配置文件。

我这样做的方法是创建一个新的Inline,模型是UserProfile,并将其添加到新的SchoolAdmin并注册它。

当我去添加新的userprofile时,我的问题出现了。会发生什么是我从下拉框中选择现有用户并单击“保存”。但是,然后我收到一条错误消息,指出“此用户的用户配置文件已存在”。

似乎在保存时,它会尝试为我选择的用户创建新的用户个人资料。我是以错误的方式做这件事吗?

以下是我设置的代码,用于在创建用户时自动创建用户配置文件。

def create_user_profile(sender, instance, created, **kwargs):
"""Create the UserProfile when a new User is saved"""
    print "User Profile Creation: False"
    if created:
        print "User Profile Creation: ", created
        UserProfile.objects.get_or_create(user=instance)



post_save.connect(create_user_profile, sender=User)
编辑:作为旁注,如何跟踪程序流程以进行调试?我发现很难处理打印语句。

1 个答案:

答案 0 :(得分:1)

我不确定你的错误是什么。但是,错误消息应该是线索。在某些时候,您已经为User X创建了一个userprofile,然后您尝试创建另一个。重要的是要注意django不会为用户自动创建配置文件,因此这必须是您编写的代码。

虽然没有看到代码,但我只是在黑暗中拍摄。请记住,他们可以通过多种方式创建这些配置文件,例如您可能在用户模型上注册了post_save信号。

至于追踪: http://docs.python.org/library/pdb.html

或者在事实崩溃调试之后有些酷,你可以尝试http://packages.python.org/django-extensions/使用http://packages.python.org/django-extensions/runserver_plus.html中的werkzeug调试器构建的实现

相关问题