I added a new UserProfile Model to my project today.
class UserProfile(models.Model):
user = models.OneToOneField(User)
...
def __unicode__(self
-
For existing users, it checks whether such an instance already exists, and creates one if it doesn't.
def post_save_create_or_update_profile(sender,**kwargs):
from user_profiles.utils import create_profile_for_new_user
if sender==User and kwargs['instance'].is_authenticate():
profile=None
if not kwargs['created']:
try:
profile=kwargs['instance'].get_profile()
if len(sync_profile_field(kwargs['instance'],profile)):
profile.save()
execpt ObjectDoesNotExist:
pass
if not profile:
profile=created_profile_for_new_user(kwargs['instance'])
if not kwargs['created'] and sender==get_user_profile_model():
kwargs['instance'].user.save()
to connect signal use:
post_save.connect(post_save_create_or_update_profile)
讨论(0)
-
You can loop through the existing users, and call get_or_create()
:
for user in User.objects.all():
UserProfile.objects.get_or_create(user=user)
You could put this in a data migration if you wish, or run the code in the shell.
讨论(0)
-
In response to your code I'll say to put a get_or_create also in a post_init listener for User.
If this "all fields null is ok" profile is just a fast example I'd put a middleware redirecting all users with no profile to the settings page asking them to fill additional data. ( probably you want to do this anyway, no one in the real world will add new data to their existing profiles if not forced or gamified into it :) )
讨论(0)
- 热议问题