3 # Copyright (C) 2013 FinalsClub Foundation
6 from allauth.account.signals import user_logged_in
7 from django.contrib.auth.models import User
8 from django.core.exceptions import ObjectDoesNotExist
9 from django.db.models.signals import post_save, pre_save
10 from django.dispatch import receiver
11 from django.db import models, DatabaseError
12 from django.middleware.transaction import transaction
13 from karmaworld.apps.courses.models import School
15 logger = logging.getLogger(__name__)
17 class UserProfile(models.Model):
18 user = models.OneToOneField(User)
20 school = models.ForeignKey(School, blank=True, null=True)
22 karma = models.IntegerField(default=0)
24 def __unicode__(self):
25 return self.user.__unicode__()
27 def user_display_name(user):
28 """Return the best way to display a user's
29 name to them on the site."""
30 if user.first_name or user.last_name:
31 return user.first_name + ' ' + user.last_name
36 @receiver(pre_save, sender=User, weak=True)
37 def assign_username(sender, instance, **kwargs):
38 # If a user does not have a username, they need
39 # one before we save to the database
40 if not instance.username:
43 # See if any other users have this email address
44 others = User.objects.get(email=instance.email)
45 except ObjectDoesNotExist:
46 instance.username = instance.email
48 instance.username = 'user' + str(random.randint(10000, 100000))
50 instance.username = 'user' + str(random.randint(10000, 100000))
53 @receiver(post_save, sender=User, weak=True)
54 def create_user_profile(sender, instance, created, **kwargs):
56 with transaction.commit_on_success():
58 UserProfile.objects.create(user=instance)
60 logger.warn("Could not create UserProfile for user {u}. This is okay if running syncdb.".format(u=instance))