How to Find Django ImageField URL

E. Sutherland picture E. Sutherland · Mar 12, 2017 · Viewed 11.3k times · Source

I'm trying to accomplish something I believed would be simple: upload an image (via admin), then use the complete URL in a template to display the image.

The problem is I can only print the relative URL: /pics/filename.jpg. I believe the sequence is settings.py (MEDIA_ROOT, MEDIA_URL), urls.py, views.py and then mytemplate.html.I hope someone can find what's missing.

Settings:
 STATIC_URL = '/static/'
 MEDIA_ROOT = '/Users/ed/code/projects/djcms/pics/'
 MEDIA_URL = '/pics/'

Urls.py:

from django.conf import settings
from django.conf.urls.static import url, static

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(r'^$/pics/', document_root = settings.MEDIA_URL)

Views.py

def detail(request, pk):
    story = Article.objects.get(pk=pk)
    my_pic = Photo.objects.get(pk=pk)
    print(story.image.url)
    print(my_pic)
    print(story.body)


    print(request)
    context = {'story': story}
    return render(request, 'articles/detail.html', context)

The Error with story.image.url:

AttributeError: 'Photo' object has no attribute 'url'

When I remove the .url, I get this partial URL:

pics/intro-bg.jpg

What am I missing? Thanks.

Answer

almost a beginner picture almost a beginner · Mar 13, 2017

This setup is working for me, maybe it will help you. It is for latest version of Django. Many answers in OS are for older Django versions.

URLS:

urlpatterns = [
#url
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Settings:

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

Template:

<img src="{{ foo.image.url }}"><br>

Model:

image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')

My foo model has an imagefield, when it is stored, I can retrieve the full url through item.image.url based on the above setup.