Dimon Kudimon
Dimon Kudimon

Reputation: 53

Django not show images

Pls tell me. Why ../static/image.jpg show images, and ../media/image.jpg now show

Need write url? Need change Setting? i dont fiend answer in documentation.

pls help.

2 night search answer.

Need upload from admin-panel photo and show in templates.

<img src="{{ tovar.product_img.url }}">

Upvotes: 0

Views: 7558

Answers (4)

chidimo
chidimo

Reputation: 2958

In Django==2.0.2 use {% get_media_prefix %}

From the docs

Upvotes: 0

Mike Sweeney
Mike Sweeney

Reputation: 1

This works (in the html img tag): src="(left squiggly, percent) static poc.image.name (percent, right squiggly):

...and thanks to whoever pointed out that ImageField has a name in addition to a (useless) path and (useless) url e.g.:

>>> from nutr.models import *
>>> poc=POC.objects.get(pk=87)
>>> poc.name

'Edgar'

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20369

In settings.py

MEDIA_ROOT = '/path/to/yourmediafolder/'
MEDIA_URL = '/media/' # whatever but it should same in `urls.py`

In urls.py

urlpatterns += patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
    'document_root': settings.MEDIA_ROOT}))

Then in template

<img src="{{ MEDIA_URL }}images/imagename.jpg"/>

Note: Here image should be as '/path/to/yourmediafolder/images/imagename.jpg'

Complete example:

I have an image test.jpg as '/home/me/test.jpg

MEDIA_ROOT = '/home/' # or /home/me/ but change url in image src
MEDIA_URL = '/media/'

#urls.py same as above

In template

<img src="{{ MEDIA_URL }}me/test.jpg"/> # or <img src="{{ MEDIA_URL }}test.jpg"/> as or condition above in MEDIA_ROOT.

Note that {{ MEDIA_URL }}me , no / between them because MEDIA_URL='/media/

You can test by:

http://domain.com/media/me/test.jpg # or  http://domain.com/media/test.jpg as OR condition in MEDIA_ROOT

in local:

http://localhost:8000/media/me/test.jpg #in locally

Upvotes: 0

Mazv&#233;l
Mazv&#233;l

Reputation: 1009

To display image you need load the static files in your template before referencing them. This is how you should display a picture in your template:

{% load staticfiles %}

<img src="{% static 'image.jpg' %}">

This image needs to be stored in your static folder. ../YourApp/YourApp/static/image.jpg is where I keep my static folder. Obviously it would be better to structure it further with images folder inside the static folder etc..

In your settings file you need the following lines:

# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

This should do the trick for you.

Upvotes: 2

Related Questions