简体   繁体   English

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

[英]Error when uploading an image to ImageField via Django Admin

Trying to upload a picture via the Django admin panel and I'm getting an error. 尝试通过Django管理面板上传图片,但出现错误。 The model is: 该模型是:

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

and the error I'm getting is: 我得到的错误是:

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']

Any ideas? 有任何想法吗?

As the error indicates, the issue id with your Picture model's __str__ method. 如错误所示, Picture模型的__str__方法的问题ID。 Instead of returning a string it is returning an ImageFieldFile object. 而不是返回字符串,而是返回ImageFieldFile对象。

Change it to return a string - eg, 更改它以返回字符串-例如,

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

or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM