Display images in Django

前端 未结 5 888
遇见更好的自我
遇见更好的自我 2020-12-11 05:53

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(m         


        
相关标签:
5条回答
  • 2020-12-11 05:58

    It looks like you may be trying to follow a video tutorial series by Corey Schaefer. If so, my suggestion won't help, but if not, Corey Schaefer has a video that covers exactly what you're trying to do at https://youtu.be/FdVuKt_iuSI?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p.

    You have to set quite a number of settings and override some defaults. The django documentation has two ways of doing it, one for development on localhost and another for production: https://docs.djangoproject.com/en/2.2/howto/static-files/

    0 讨论(0)
  • 2020-12-11 05:59

    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">
    
    0 讨论(0)
  • 2020-12-11 06:01

    The template tag should be:

    <img src="{{ post.images.img.url }}" ... >
    
    0 讨论(0)
  • 2020-12-11 06:09

    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.
    0 讨论(0)
  • 2020-12-11 06:16

    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 %}
    
    0 讨论(0)
提交回复
热议问题