python – (Django)无法分配“u’1”“:”StaffProfile.user“必须是”用户“实例

前端之家收集整理的这篇文章主要介绍了python – (Django)无法分配“u’1”“:”StaffProfile.user“必须是”用户“实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个如下所示的模型:
class StaffProfile(models.Model):
    user = models.ForeignKey(User)
    maas = models.FloatField()
    maas_gunu = models.CharField(max_length=5)

当我尝试使用如下代码插入数据时:

staffprofilesay = StaffProfile.objects.filter(user = user_id).count()

     if staffprofilesay > 0:
        staffprofile = StaffProfile.objects.get(user = user_id)
     else:    
        staffprofile = StaffProfile()

     staffprofile.user = user_id
     staffprofile.maas = calisan_formu.cleaned_data["maas"]
     staffprofile.maas_gunu = calisan_formu.cleaned_data["maas_gunu"]
     staffprofile.save()

我得到如下错误

Cannot assign "u'1'": "StaffProfile.user" must be a "User" instance.

我应该做些什么?

PS:我正在使用Django的用户模型

解决方法

您需要分配一个User对象,例如
from django.contrib.auth.models import User
user = User.objects.get(id=user_id)

staffprofile.user = user

猜你在找的Python相关文章