Django:“Can not convert'Name'object to str implicitly”保存对象 [英] Django: "Can't convert 'Name' object to str implicitly" on saving object
问题描述
在Django管理员中,我创建了一个名称对象,名称为英国。然后我创建一个使用我刚创建的Name对象的国家对象,并创建一个标志图像的路径。
In Django admin, I have created a Name object with name: "United Kingdom". I then create a Nation object with the Name object I've just created, and a path to a flag image.
在保存条目时,我得到:
On saving the entry, I get:
Can't convert 'Name' object to str implicitly
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/display/nation/add/
Django Version: 1.6.2
Exception Type: TypeError
Exception Value: Can't convert 'Name' object to str implicitly
Exception Location: \models.py in __unicode__, line 24
相关model.py
Relevant section of models.py
class Name(models.Model):
def __unicode__(self):
return 'Name: ' + self.name
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
class Meta:
db_table = 'name'
class Nation(models.Model):
def __unicode__(self):
return 'Nation: ' + self.name
id = models.AutoField(primary_key=True)
name = models.ForeignKey(Name)
flag_path = models.CharField(max_length=64)
class Meta:
db_table = 'nation'
从错误消息中我明白返回'Name:'+ self.name
需要获取一个字符串追加到'Name:',但是我如何修改我的models.py来允许?
From the error message I understand that return 'Name: ' + self.name
needs to get a string back to append to 'Name: ', but how would I amend my models.py to allow that?
推荐答案
修复问题的更改:
'名称: '+ self.name.name
'Name: ' + self.name.name
这样我正确地引用名称表中的名称列。
That way I'm correctly referring to the name column in the name table.
这篇关于Django:“Can not convert'Name'object to str implicitly”保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!