Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? Here is what I tried :

my view:

#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT

def home(request):
    latest_images = Image.objects.all().order_by('-pub_date')
    return render_to_response('home.html',
                             #{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
                             {'latest_images':latest_images,},
                             context_instance=RequestContext(request)
                             )

my model:

class Image(models.Model):
    image = models.ImageField(upload_to='imgupload')
    title = models.CharField(max_length=250)
    owner = models.ForeignKey(User)
    pub_date = models.DateTimeField(auto_now=True)

my template:

{% for image in latest_images %}
    <img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}

and my settings.py MEDIA_ROOT and URL:

MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'

So again here is what I am trying to do: Use those images in my templates!

like image 755
Tony Avatar asked Dec 21 '22 23:12

Tony


1 Answers

If you use the url attribute, MEDIA_URL is automatically appended. Use name if you want the path without MEDIA_URL. So all you need to do is:

<img src="{{ some_object.image_field.url }}">
like image 97
Chris Pratt Avatar answered Jan 14 '23 17:01

Chris Pratt