dsbonafe
dsbonafe

Reputation: 315

How to upload photo in Django

I have a small problem with django here. 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:

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:

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:

{% 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. In web page appears the follow:

Capture of my screen

Could someone help me?

Thank you a lot.

Upvotes: 0

Views: 95

Answers (2)

crash843
crash843

Reputation: 670

Problem is in your template. Try {{ produto.foto.image.url }} instead of {{ produto.foto.url }} to access to image file url.

Upvotes: 1

Pythonista
Pythonista

Reputation: 11615

It looks like you haven't set your media root or added the url configurations hence they're not being served. You can check out how to set these up at the documentation

Upvotes: 1

Related Questions