Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find Django ImageField URL

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.

like image 419
E. Sutherland Avatar asked Oct 23 '25 04:10

E. Sutherland


1 Answers

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.

like image 96
almost a beginner Avatar answered Oct 25 '25 19:10

almost a beginner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!