Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a model like below:

class StaffProfile(models.Model):
    user = models.ForeignKey(User)
    maas = models.FloatField()
    maas_gunu = models.CharField(max_length=5)

When I try to insert data with a code like below:

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

I get an error like this:

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

What am I supposed to do?

PS: I'm using Django's User model

like image 652
Eren Süleymanoğlu Avatar asked Mar 08 '12 10:03

Eren Süleymanoğlu


1 Answers

You need to assign a User object e.g.

from django.contrib.auth.models import User
user = User.objects.get(id=user_id)

staffprofile.user = user
like image 83
JamesO Avatar answered Oct 24 '22 01:10

JamesO