我有一个userprofile模型
class UserProfile(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField(max_length = 50, blank = True,null = True)
def __str__(self):
return "%s's profile" % self.user
我的观点是
@login_required()
def score(request):
if request.is_ajax():
print request.method
if request.method == 'GET':
try:
user1 = UserProfile.objects.get(user=request.user)
print user1
user1.score = request.GET.get('bjpFan')
user1.save()
print user1.score
print "rahul"
return HttpResponse("%s" % user1.score )
except UserProfile.DoesNotExist:
print "Gaurav"
user1 = create_user()
return HttpResponse("%s" % user1.score )
因此得分存储到数据库,但是当新用户使用此应用程序时,他的对象不会被存储。如果用户第一次使用此应用程序,则需要为用户创建新对象。 我也创建了userprofile对象。
def create_user(username, email = None, password = None):
try:
user = User.objects.get(username=username)
except:
user = User(username=username,email=email)
user1=UserProfile(user=user.request, score=user.score)
user.save()
user1.save()
return user
但是当新用户访问此应用程序时,他的名字和分数不会被存储。他的所有facebook数据都存储在facebook模型中。 请帮帮我。
答案 0 :(得分:1)
最强大的方式是使用信号:
class UserProfile(models.Model):
user = OneToOneField( User, editable = False ) #<----One to One! Not FK.
score = models.IntegerField(max_length = 50, default = 0)
#
# this few lines of code in your UserProfile models.py will
# create the profile just after user is created.
#
from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=User)
def createProfile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create( user = instance, )