通过Django Admin将图像上传到ImageField时出错

时间:2016-06-23 02:43:42

标签: python django python-3.x imagefield

尝试通过Django管理面板上传图片,我收到了错误消息。该模型是:

fs = FileSystemStorage(location='/media')

class Picture(models.Model):
    picture_path = models.ImageField(upload_to=fs, blank=True)
    hunter_ID = models.ForeignKey(User,
                                  on_delete=models.CASCADE,)
    bounty_ID = models.ForeignKey('bountyhunt.Bounty',
                                  on_delete=models.CASCADE,)
    winner = models.BooleanField(default=False)
    example_pic = models.BooleanField(default=False)

    def __str__(self):
        return self.picture_path

我得到的错误是:

TypeError at /admin/hunt/picture/add/
__str__ returned non-string (type ImageFieldFile)
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/hunt/picture/add/
Django Version: 1.9.6
Exception Type: TypeError
Exception Value:    
__str__ returned non-string (type ImageFieldFile)
Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/encoding.py in force_text, line 76
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.5/bin/python3
Python Version: 3.5.1
Python Path:    
['/Users/michael/Documents/phoboh',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

如错误所示,问题标识为Picture模型的__str__方法。它不是返回一个字符串,而是返回一个ImageFieldFile对象。

更改它以返回字符串 - 例如

def __str__(self):
    return str(self.picture_path)

或:

def __str__(self):
    return self.picture_path.name