I am completely beginner in Django, trying to make a table, which gets data from the Django database(included image). Here before adding the image field in the Django model, all was working perfectly. but I cannot get an image from the Django media file(I also upload images with superuser and Django form both, and they worked perfectly). here is my approach below-
in views.py:
def index(request):
table_data = TableA.objects.order_by('roll')
index_dict = {'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
}
return render(request, 'app26/index.html', context=index_dict)
in HTML:
{% if dynamic_table %}
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Roll</th>
<th>Email</th>
<th>Password</th>
<th>Address</th>
<th>Profile Pic</th>
</tr>
</thead>
<tbody>
{% for i in dynamic_table %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.roll }}</td>
<td>{{ i.email }}</td>
<td>{{ i.password }}</td>
<td>{{ i.address }}</td>
<td><img class="profile-pic" src="{{media_url}}{{ i.profile_pic }}" alt=""></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>sorry cannot load the data for technical error</p>
{% endif %}
in urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
I've also set up MEDIA_URL and MEDIA_ROOT. From the Admin I can upload images and they are ok. in settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'Media')
MEDIA_URL = '/images/'
Now my problem is nothings is show in the profile pic column in the table, even any error is not showing. Please suggest me how can I get the image file from the database for my this uses
I think the main reason the images where not being displayed was because the path to your media_url was not added into the render
function. See below:
def index(request):
img = Upload.objects.filter(file_type='image')
index_dict = {
'insert_me' : "hello this is from views.py",
'dynamic_table' : table_data,
'media_url': settings.MEDIA_URL
}
return render(request, 'app26/index.html', context=index_dict)
Give it a shot!