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:
TypeError at /admin/display/nation/add/
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
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'
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?
Use unicodes in
__unicode__()
method i.e.and
Without unicode in
'Nation: ' + self.name
, it will try to get string representation which is not defined forName
object.The change that fixed the problem:
'Name: ' + self.name.name
That way I'm correctly referring to the name column in the name table.