Home > Mobile >  Change django picture img src in template based on min-width
Change django picture img src in template based on min-width

Time:12-15

I wasn't sure how to ask this question. Want to send correctly sized images to different screens from my django application. I have it so that when an image is uploaded, that it is saved to media but with multiple sizes.

media

So, the image above shows in my media/uploads/pieces/{ID}/Sargent.jpg and all of it's other sized images. The models imageField is pointing to the "original" file without an underscore and width.

templates/art/piece_detail.html

<picture>
    <source media="(min-width:300px)" srcset="{{ piece.image.url ??? }}">
    <source media="(min-width:375px)" srcset="{{ piece.image.url ??? }}">
    <source media="(min-width:786px)" srcset="{{ piece.image.url ??? }}">
    <source media="(min-width:1440px)" srcset="{{ piece.image.url ??? }}">
    <img src="{{ piece.image.url }}" alt="{{ piece.name }} - {{ piece.height }} x {{ piece.width }}">
</picture>

Then here I am using an HTML <picture> tag with some source medias to be how I serve the appropriate image. However I am at a loss on maybe the best way to do what I am trying to accomplish. I realize these break points are probably not exactly what I need, but just trying to get my idea across.

I thought about adding more "path" fields to the Piece model and set them to these other URL paths too, but that seems like a sloppy solution to this. Otherwise, I think I would need to do some string manipulation in the view before it gets to the template...

Additionally what are today's standard image break points?

Thanks in advance!

CodePudding user response:

you can create a custom filter

that accepts the image url and specific width and return the URL with the width plugged in.

def format_img_src(img_ur, size):
    """Returns an image of specific size"""
    # do your formatting here

CodePudding user response:

class my_model_name(models.Model):
    ......
    image = models.ImageField(default='default.jpg', upload_to = '')

def save(self, *args, **kwargs):
    super(my_model_name, self).save(*args, **kwargs)
    img = Image.open(self.image.path)

    if img.height>300 or img.width > 300:
        img.thumbnail( (300,300) )
        img.save(self.image.path)

If you use this save mathod than your all img save 300*300.you can chane your size .

  • Related