Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

Why do I receive a django error when trying to create a model instance with a foreign key?

I am receiving the following error:

ValueError: Cannot assign "u'ben'": "Entry.author" must be a "MyProfile" instance.

From this line:

form.author = request.session['username']

Note: Entry.author is a foreign key as seen below.

models.py

class MyProfile(models.Model):
    user = models.CharField(max_length=16)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def __unicode__(self):
        return u'%s %s %s' % (self.user, self.firstname, self.lastname)

class Entry(models.Model):
    headline= models.CharField(max_length=200,)
    body_text = models.TextField()
    author=models.ForeignKey(MyProfile, related_name='entryauthors')

    def __str__(self):
        return u'%s %s %s' % (self.headline, self.body_text, self.author)

The error says Entry.author must be a "MyProfile" instance, but when I go into the django shell and run a query, I see an instance exists with username ben.

<QuerySet [<MyProfile: ben ben    97201  None>]>

I am now wondering if request.session['username'] is maybe not returning a correctly formatted username and I have no way to test this (that I know of) in the django shell because I don't think you can access the request object from the shell.

In my login form, I have this line which is passing the username to the request.session.

if form.is_valid():
    username = form.cleaned_data['username']
    request.session['username'] = username
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

form.author must be a MyProfile instance while request.session['username'] is a string. You may need to do a query selecting the Author such as form.author = MyProfile.objects.get(user=request.session['username'])

To prevent DoesNotExist error, you can do as follow:

try:
   form.author = MyProfile.objects.get(user=request.session['username'])
except MyProfile.DoesNotExist:
    form.author = None

Side Note: There is no username in MyProfile model so I assume it matches with the name


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...