我已经在 Django 1.4.5 上使用了 UserProfiles。它可以工作,但现在我希望能够在创建用户时在管理员的自定义字段中添加一个值。这种工作方式,我需要创建新用户,然后返回并添加 UserProfile 字段。
在创建用户时添加 UserProfile 字段需要在哪里以及需要做什么?
### admin.py
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
# Something here?
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
### models.py
class UserProfile(models.Model):
"""Create additional fields for users.
Site ID
"""
# This field is required
user = models.OneToOneField(User)
# Additional fields to add.
site_id = models.IntegerField(null=True, blank=True, verbose_name='Site ID')
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Or maybe here?
post_save.connect(create_user_profile, sender=User)