3 # Copyright (C) 2013 FinalsClub Foundation
5 from allauth.account.signals import user_logged_in
6 from django.contrib.auth.models import User
7 from django.core.exceptions import ObjectDoesNotExist
8 from django.db.models.signals import post_save, pre_save
9 from django.dispatch import receiver
10 from django.db import models
11 from karmaworld.apps.courses.models import School
14 class UserProfile(models.Model):
15 user = models.OneToOneField(User)
17 school = models.ForeignKey(School, blank=True, null=True)
19 karma = models.IntegerField(default=0)
21 def __unicode__(self):
22 return self.user.__unicode__()
24 def user_display_name(user):
25 """Return the best way to display a user's
26 name to them on the site."""
27 if user.first_name or user.last_name:
28 return user.first_name + ' ' + user.last_name
33 @receiver(pre_save, sender=User, weak=True)
34 def assign_username(sender, instance, **kwargs):
35 # If a user does not have a username, they need
36 # one before we save to the database
37 if not instance.username:
40 # See if any other users have this email address
41 others = User.objects.get(email=instance.email)
42 except ObjectDoesNotExist:
43 instance.username = instance.email
45 instance.username = 'user' + str(random.randint(10000, 100000))
47 instance.username = 'user' + str(random.randint(10000, 100000))
50 @receiver(post_save, sender=User, weak=True)
51 def create_user_profile(sender, instance, created, **kwargs):
53 UserProfile.objects.create(user=instance)