How to Include Image Files in Django Templates

How do I include image files in Django templates?

In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example

<img src="../media/foo.png">

And then you'll just make sure that directory is there with the relevant file(s).

during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.

Right here.

Adding an image into a django template from the static folder - Django

load staticfiles tag to template after extends

{% extends "base.html" %}
{% load staticfiles %}

and then use it in src attribute of img HTML tag

<img src="{% static 'images/Artboard1.png'%}" alt="Sample Image">

display image from django model to template using for loop

First, you're not following Python convention: A class should be Capitalized (Pascal Case) and an attribute should be a lowercase :

class Product(models.Model):
name = models.CharField(max_length=700, null=True)
price = models.FloatField(null=True)
link = models.URLField(max_length=2000, null=True)
image = models.ImageField(null=True)

To answer the question, make sure you have done the followings:

urls.py

urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Template

<img src="{{ product.image.url }}">

Model:

image = models.ImageField(upload_to = 'product-img/', null=True)

If the image is saved, you'll find it in folder media/product-img

How can I return image address to Django template from a function of the file views.py?

We just have to make changes in return line, it should be as follows:-

return HttpResponseRedirect(filepath)

It worked fine after using it !!

How can I use user uploaded files in my templates? (django)

On development machine, you need to tell the devserver to serve uploaded files

# in urls.py
from django.conf import settings

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

{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}

# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
latest_images = Image.objects.order_by('-pub_date')
return render(request, 'home.html', {'latest_images':latest_images})

On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. Also configure the webserver to read /media/filename from correct path.



Related Topics



Leave a reply



Submit