pythondjangodjango-modelsdjango-formsdjango-file-upload

Is there a way to use files uploaded in django in the template?


I have a django model form where I uploaded images for my app. I am just storing them temporarily locally since its not a real project. The Admin looks like this I'm wondering if there is a way to use the images uploaded with each object in the template. I cant find any articles. How can I make a link to what images are associated with what models?

enter image description here


Solution

  • Yes you can access it through object.photo.url

    I'll show u some random example.

    Since I can't see the name of your model, let's pretend that it's called Post.

    In views.py you can send your post objects to the templates (I guess you probably know this already)

    view.py | example snippet

    from django.views.generic import TemplateView
    from .models import Post
        
    
    class IndexView(TemplateView):
        template_name = 'yourapp/index.html'
            
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['posts'] = Post.objects.all()
            return context
    

    and then you could display it in the templates as following

    index.html | example snippet

    {% for post in posts %}
       <img src="{{ post.photo.url }}" alt="..." class="..." />
    {% endfor %}