gpt4 book ai didi

python - 想保存每个用户django的数据

转载 作者:行者123 更新时间:2023-11-28 18:43:41 24 4
gpt4 key购买 nike

我有用户配置文件模型

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 模型中。请帮助我。

最佳答案

最稳健的方法是使用信号:

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, )

关于python - 想保存每个用户django的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com