Reputation: 478
I'm trying to make a gallery website but I cannot seem to retrieve the images to display in the html. I'm trying to retrieve images from the database based on a filter_type
which has value as image.
So far I have this:
In views.py
def gallery(request):
img = Upload.objects.filter(file_type='image')
return render(request,'gallery.html',{"img":img})
and in html
:
{% for n in img %}
<img src="{{ n.img}}" />
{% endfor %}
My models.py
is as follow:
class Upload(models.Model):
image = models.ImageField(upload_to='media/image',default='')
text_field = models.CharField(max_length=200,default='')
date_added = models.DateTimeField(auto_now_add=False,auto_now=True)
file_type = models.CharField(max_length=256, choices=[('image', 'image'), ('video', 'video'), ('other', 'other')])
class Meta:
verbose_name_plural = "Files Manager"
I've also set up MEDIA_URL
and MEDIA_ROOT
. From the Admin I can upload images and they are ok.
my MEDIA_URL
:
MEDIA_ROOT = os.path.join(BASE_DIR,'static','media')
MEDIA_URL = '/media/'
When I view the html the src
path is empty.
Upvotes: 4
Views: 17519
Reputation: 1
Save your image in static/upload/image folder in pycharm. And then use
<img src="../../static/upload/Image-name"/>
in your html page
Upvotes: 0
Reputation: 478
Problem solved.
The main reason the images where not displayed in my html was because the path was wrong. I should have took it from my media_url + name of the file, ,since media_url was not added, there was no path to be displayd correctly. The correct way it was:
for VIEWS.py :
def gallery(request):
img = Upload.objects.filter(file_type='image')
return render(request,'gallery.html',{"img":img, 'media_url':settings.MEDIA_URL})
and for html
:
{% for i in img %}
<img src="{{media_url}}{{ i.image }}">
{% endfor %}
Hopefuly this answers somebody's question or if not at least I can go on now.:) thanks all for support.
Upvotes: 6