简体   繁体   English

如何在Django中上传照片

[英]How to upload photo in Django

I have a small problem with django here. 我在这里有django的小问题。 I want to upload a photo of one product in production and want that this photo be shown to me in homepage. 我想上传生产中一种产品的照片,并希望在主页上显示该照片。

Here is the Product class in models.py : 这是models.pyProduct类:

class Produto(models.Model):

    nome = models.CharField(max_length=255, null=False)
    foto = models.ImageField(upload_to='mywebsite/staticfiles/static')


    def __unicode__(self):
        return "%s" % (self.nome)

In my settings.py , I've set these variables: 在我的settings.py ,设置了以下变量:

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

And in my htm page: 在我的htm页面中:

{% for produto in produtos %}
    <li>
        <div class="col-md-3 biseller-column">
            <a href="single.html">
                <img src="{{produto.foto.url}}"/>
            </a>
            <div class="ad-info">
                <h5>{{produto.nome}}</h5>
            </div>
        </div>
    </li>
{% endfor %}
</ul>

So, I get my upload and when I upload via web browser the photo appears on staticfiles/static but in not in the site. 因此,我得到了上传,并且当我通过Web浏览器上传时,照片显示在staticfiles / static上,但不在站点中。 In web page appears the follow: 在网页中出现以下内容:

捕捉我的屏幕

Could someone help me? 有人可以帮我吗?

Thank you a lot. 非常感谢。

It looks like you haven't set your media root or added the url configurations hence they're not being served. 您似乎尚未设置媒体根目录或添加了url配置,因此无法提供它们。 You can check out how to set these up at the documentation 您可以在文档中查看如何进行设置

Problem is in your template. 问题出在您的模板中。 Try {{ produto.foto.image.url }} instead of {{ produto.foto.url }} to access to image file url. 尝试使用{{ produto.foto.image.url }}而不是{{ produto.foto.url }}来访问图像文件url。

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

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