为什么尝试使用外键创建模型实例时会收到django错误? [英] Why do I receive a django error when trying to create a model instance with a foreign key?
问题描述
我收到以下错误:
ValueError: Cannot assign "u'ben'": "Entry.author" must be a "MyProfile" instance.
从此行:
form.author = request.session['username']
注意: Entry.author是一个外键,如下所示。
Note: Entry.author is a foreign key as seen below.
models.py
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)
错误说Entry.author必须是一个MyProfile实例,但是当我进入django shell并运行一个查询,我看到一个实例存在用户名ben。
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>]>
我现在想知道request.session ['username']是否可能没有返回正确格式的用户名我没有办法在django shell中测试(我知道的),因为我不认为你可以从shell访问请求对象。
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.
我的登录表单,我有这行将用户名传递给request.session。
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
推荐答案
只要我使用它,外键将成为每个类中的共享对象位置(请原谅我自己的毛孔术语,授课)。
As far as i have used it, the "foreign key" is to be a shared object location in each class (please excuse the pore terminology I am self-taught).
一个示例代码如下:
class One():
key1 = models.CharField(max_length=150)
class Two():
key1 = models.ForeignKey(key1)
我希望这有帮助。
https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py
line 52
https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py line 52
-Cheers
这篇关于为什么尝试使用外键创建模型实例时会收到django错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!