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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…