ChocoBomb
ChocoBomb

Reputation: 301

Django : Display uploaded image with media

I would like to display in my template the uploaded picture for each object. I'm getting an issue because there is an error with media path when I click over picture url.

I have in my model :

class Publication(models.Model):
    ...
    cover = models.ImageField(upload_to='media/', verbose_name=_('cover page'))

Then, I have in my settings part :

MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR + '/myapp/'

Now, in my template file, I display the picture like this :

{% if item.cover %}
    <td>
        <a href="{{item.cover.url}}" target="_blank">
            <img class="glyphicon glyphicon-home" src="{{item.cover.url}}" alt="{{item.cover}}">
        </a>
    </td>
{% else %}
    <td></td>
{% endif %}

enter image description here

The template page url is : http://localhost:8000/crud/publication/list/ And when I click on my picture link, I get : http://localhost:8000/crud/publication/list/media/media/couverture_qZQKLED.jpg

It's false and I should get :

http://localhost:8000/media/couverture_qZQKLED.jpg

Then, I would like ti replace visible elements just by a glyphicon.

Could you help me ?

In my urls.py file, I have :

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Upvotes: 3

Views: 4577

Answers (2)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

Correct configuration for media files in settings.py

# Media files, uploaded by user
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Template

<a href="{{item.cover.url}}" target="_blank">
    <!-- An alt tag in span makes no sense, so you can use title tag if you want. -->
    <span class="glyphicon glyphicon-home" title="{{item}}"></span>
    <!-- OR show item's str inside span -->
    <span class="glyphicon glyphicon-home">{{item}}</span>
</a>

Upvotes: 2

aman kumar
aman kumar

Reputation: 3156

you have add the upload_to='media/', in the image fields so it will create one more folder inside your media root. Django already media in image path. complete path become mediaurl+folderpath

cover = models.ImageField(upload_to='other_folder_name', verbose_name=_('cover page'))

and

MEDIA_URL = '/media/'

because it take relative path, without start with /

<a href="{{item.cover.url}}" target="_blank">
        <span class="glyphicon glyphicon-home" alt="{{item.cover}}"></span>
</a>

Upvotes: 2

Related Questions