images id -> url

Hey there.

I would like to display each image individually in the url by their id (images are stored in media file and their path is in the DB) . Something like : http://…/image/4 for example.
So far, my code is displaying all the images in the template. Now I’m stuck at displaying them individually. This is what I’ve got so far:

views.py

def cropper(request):
    obj = Path.objects.all()
    context = {'obj':obj}
    return render(request,'images.html',context)

models.py

class Path(models.Model):
    image_path = models.CharField(max_length=200)

    def __str__(self):
        return str(self.id)

template

{% for ob in obj %}

    <img src="{{ ob.image_path }}" id="image" width="300px" height="200px" >

{% endfor%}

urls.py

urlpatterns = [
    
path('image/<int:image_path>', cropper, name="cropper"),  ---- Not sure about this part.
    ]

Thanks for any ideas about how to achieve this.

Start with your view - what are you doing in your current view that would cause you to display all images? What do you think you can do that would only display one image?

views.py

def cropper(request,id):
    obj = Path.objects.get(id=id)
    print(obj)
    context = {'obj':obj}
    return render(request,'images.html',context)

#urls.py

path('crop/<int:id>', cropper, name="cropper"),

templates

<img src="{{ obj.image_path }}" id="image" width="300px" height="200px" >

close… The template works when the id exists but it doesn’t display the image.

What is rendered in the src attribute of the img tag on that page?

The path to the image. For example: media/converted/page_5.jpeg.

When I use: http://127.0.0.1:8000/crop/26/ then I get the error is: Not Found: /crop/26/media/converted/page_5.jpeg

Ok, so it’s not a problem with your view or template, it’s a data issue - you’re requesting a file that is not in the location being requested.

Superficially, what it looks like what the problem might be is that the path you’re rendering is specified as a relative path and not an absolute path. You probably want that path stored as /media/converted/page_5.jpeg

2 Likes

Yes Sr. You were right. Thank you for your time.