How to Find Django ImageField URL

14,103

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:

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

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.

Share:
14,103
E. Sutherland
Author by

E. Sutherland

Updated on June 04, 2022

Comments

  • E. Sutherland
    E. Sutherland almost 2 years

    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.

  • E. Sutherland
    E. Sutherland about 7 years
    The change still displays only the relative URL: pics/filename.jpg
  • E. Sutherland
    E. Sutherland about 7 years
    Solved. In my template: <img src={{MEDIA_URL}}{{my_pic}}"/>