pythondjangoviewmedia-url

Django 1.6 image upload and media path


So I have a project on webfaction where I need to create two different environments, one to server django and one to server static files.

So when I upload an image from admin panel I can see the image is placed in root i defined but with full path. When i return the image in my view i get my domain.com/full/media/root/path/imagename

this generates a broken link - when i go to mydomain.com/uploads/image_name, I can see image file is there however my link is pointing to full path rather than root_url,

Could you please help me with this? I really dont understand how i can correct this image link in my view

<img src="{{ MEDIA_URL }}{{ mymodel.my_image }}" alt="{{ name }}" width="150" height="200" />

I do understand there are so many subjects similar to this here however none of them could direct me correctly in regards to how to hide or change path root to "uploads"

I have which works fine in my admin

class Movie(models.Model):

name = models.CharField(max_length=50)


def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join( '/home/user/webapps/project/uploads/' , filename)


my_image = models.ImageField(upload_to = get_file_path, null=True, blank=True)
def __unicode__(self):
    return self.name

In my settings:

MEDIA_ROOT = '/home/user/webapps/project/uploads/'
MEDIA_URL = '/uploads/'

and project url:

from django.conf.urls import patterns, include, url from django.conf import settings

  from django.contrib import admin
  admin.autodiscover()

  urlpatterns = patterns('',      
    url(r'^admin/', include(admin.site.urls)),
  )


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

Thank you all in advance


Solution

  • At first for your model you should create an image field and in there you should define where you want to upload your image:

    class mymodel(models.Model):
        name = models.CharField(max_length=50)
        my_image = models.ImageField(blank=True, null=True,upload_to='/home/user/webapps/project/uploads/')
    

    After that in your template when you want to show your image after getting your model object from your database try this:

    <img src="{{ mymodel.my_image.url }}" alt="{{ mymodel.name }}" width="150" height="200" />