Reputation: 33
How do I display images from media file instead of database? Specifically I want it to load images uploaded by users from media_cdn
. I feel like only the views.py require changes but I'm not sure if other areas should be changed as well.
Here are my Django codes
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn')
views.py
def imgdownload(request):
allimages = ImagefieldModel.objects.all()
return render(request, 'main/show.html',{'images': allimages})
urls.py
urlpatterns = [
....
....
path("show/", views.imgdownload, name="imgdownload"),
.... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class ImagefieldModel(models.Model):
title = models.CharField(max_length = 200)
img = models.ImageField(upload_to = "media")
class Meta:
db_table = "imageupload"
show.html
{% extends "main/header.html" %}
{% load static %}
{% block content %}
<head>
<title>Django Display Images</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Image</th>
</tr>
</thead>
<tbody>
{% for img in images %}
<tr>
<td>{{img.title}}</td>
<td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
{% endblock %}
Any help is much appreciated.
Upvotes: 2
Views: 1406
Reputation: 177
You can to use "url": {{ ìmg.img.url }}
, in your example, to change for this:
<td><img src="{{ img.img.url }}" width="120"/></td>
All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You’ll most likely want to use the convenience url attribute provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.
Upvotes: 1