Display images in Django

2019-02-25 08:44发布

I have a django app which allows users to submit an image with it. Right now my model looks like

class Posting(models.Model):
    title = models.CharField(max_length=150)
    images = models.ForeignKey(Image, null=True)

class Image(models.Model):
    img = models.ImageField(upload_to="photos/",null=True, blank=True)

and I am trying to display the images in my template however I cannot seem to get it to work. I have gone though countless stack overflow posts and haven't had any luck. In my template I have

{ for post in postings }
    <img src"{{ post.image.url }} #and many variations of this

however other seems to display the url. The url seems to always be blank. Any help would be greatly appreciated!

4条回答
狗以群分
2楼-- · 2019-02-25 09:25

This is how i got it working.

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_ROOT = (
BASE_DIR
)


MEDIA_URL = '/media/'

models.py ...

image = models.ImageField(upload_to='img')

urls.py(project's)

if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

template (.html)

<img src="{{ post.image.url }}" alt="img">
查看更多
狗以群分
3楼-- · 2019-02-25 09:27

The template tag should be:

<img src="{{ post.images.img.url }}" ... >
查看更多
男人必须洒脱
4楼-- · 2019-02-25 09:29

You should expect something akin to:

{% for post in postings %}
  <img src="{{ post.image.url }}">
{% endfor %}

There are a couple of caveats here --

  • Images are served as a file, whatever is serving your application (runserver, nginx, apache, etc.) needs to have the ability to route that file.
  • You must ensure you are building the context for the template engine to use. It will silently fail on values that it cannot find in context.
查看更多
Summer. ? 凉城
5楼-- · 2019-02-25 09:31

Do something like this. This code is working in my app.

views.py:

def list(request):
  images = Image.objects.all()
  return render(request, "list.html", {'images': images})

list.html:

{% for i in images %}
    <img src="{{ i.image.url }}" width="500px"/>
{% endfor %}
查看更多
登录 后发表回答