开发者

Problem with Adding/Editing inline Foreign Key Fields in Django Admin

开发者 https://www.devze.com 2023-03-20 19:47 出处:网络
I have two models, School and UserProfiles, where UserProfiles has a ForeignKey to School. In the Django Admin, I want to be able to pick a school and have it display all the userprofiles that have a

I have two models, School and UserProfiles, where UserProfiles has a ForeignKey to School. In the Django Admin, I want to be able to pick a school and have it display all the userprofiles that have a foreign key to it.

The way that I开发者_Go百科 did this was to create a new Inline, with the model being the UserProfile, and adding it to the new SchoolAdmin and registering it.

My problem arises when I go to add a new userprofile. What happens is that I pick an existing user from the dropdown box and click save. However, I then get an error stating that a "User Profile with this User already exists."

It seems that upon saving, it tries to create a new User Profile for the user I pick. Am I going about doing this the wrong way?

Here is the code that I have set up to auto-create the user profiles when a user is created.

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)

EDIT: As a side-note, how can I go about tracing the program flow for debugging? I find it difficult to deal with just print statements.


I'm not sure what you have set up wrong. However, the error message should be the clue. At some point you've created a userprofile for User X and then you've tried to create another. It's important to note that django does not autocreate profiles for users so this has to be code that you've written.

Without seeing code I'm just shooting in the dark here though. Keep in mind their are multiple ways you could be creating these profiles such as perhaps you registered the post_save signal on the user model.

As for tracing: http://docs.python.org/library/pdb.html

Or for some cool after the fact crash debugging you could try http://packages.python.org/django-extensions/ with it's implementation of the werkzeug debugger build in http://packages.python.org/django-extensions/runserver_plus.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号