Search code examples
pythonhtmldjangoimagefieldfilefield

How to properly display images to html template in Django framework?


I've been trying for a day to try to get the images that are saved to the media folder to display in my template file, but to no avail. The images are uploaded to the media/images folder, but I can't figure out how to display them. I can't figure out what I'm doing wrong because I see many people use these methods and get a result. I'm thinking maybe my post function isn't returning the correct data to the template? I'm extremely new in Django and html, so please forgive my mistakes.

This is my current setup:

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

models.py

from django.db import models

class Post(models.Model):
    post = models.ImageField(upload_to="images")

forms.py

from django import forms
from imageDetection.models import Post

class HomeForm(forms.ModelForm):
    class Meta: 

        model = Post 
        fields = ('post',)

views.py

class HomeView(TemplateView):
    template_name = 'imageDetection/test.html'

    @staticmethod
    def detect(request):
        return render(request, 'imageDetection/detection.html')

    def get(self, request): 
        form = forms.HomeForm()
        return render(request, self.template_name, {'form': form})

    def post (self, request):
        context = {}
        if request.method == "POST":
            form = forms.HomeForm(request.POST, request.FILES)
            if form.is_valid():
                image_form = models.Post()
                image_form.post = form.cleaned_data['post']
                image_form.save()
                context['form'] = image_form
                return render (request, 'imageDetection/detection.html', context)
            else: 
                form = forms.HomeForm()
                context['form'] = form
        return render(request, self.template_name, context)

urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('imageDetection.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

template/ Detection.html

{% for post in form %}
    {% if post.image %}
        <img src="{{ MEDIA_URL }}{{ post.image.url }}" />
    {% endif %}
{% endfor %}

Thank you, any help will be appreciated


Solution

  • Here I didn't see any field with name image in your model.You have define the image with field name post .

     {% if post.post %}
            <img src="{{ post.post.url }}" />
     {% endif %}
    

    And also here better use the meaningful variable for your fields and context.You can name your image field with image instead of post and context images instead of forms