The change that fixed the problem:
'Name: ' + self.name.name
That way I'm correctly referring to the name column in the name table.
Question
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
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'
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?
Solution 2
The change that fixed the problem:
'Name: ' + self.name.name
That way I'm correctly referring to the name column in the name table.
OTHER TIPS
Use unicodes in __unicode__()
method i.e.
u'Name: ' + self.name
and
u'Nation: ' + self.name
Without unicode in 'Nation: ' + self.name
, it will try to get string representation which is not defined for Name
object.