displaying all images from directory Django

后端 未结 2 1852
野的像风
野的像风 2021-01-25 11:28

I am not sure how to display images from a directory onto a page. I am trying to create a gallery app. I am I am trying to do this bit by bit. My goal would be to create a thumb

2条回答
  •  花落未央
    2021-01-25 11:57

    In Django you should use ImageField and define function that will generate "upload_to" parameter for your image :

    def images_upload_to(instance, filename):
        return '/'.join(['images', instance.album.title])
    
    class Image(models.Model):
        title = models.CharField(max_length = 60, blank = True, null = True)
        tags = models.ManyToManyField(Tag, blank = True)
        albums = models.ForeignKey(Album, blank = True)
        img = models.ImageField(upload_to=images_upload_to,null=True,blank=True)
    

    demensions of image you can access in template by {{ image.img.height }} and {{ image.img.width }}

    In this solution you cant use ManyToManyField to albums, becouse your directory structure is opposing it. If you wish to use ManyToManyField your images_upload_to function can't/shouldn't generate directory path based on one album. And in the first place, gallery images shouldn't be stored in static directory, but in media. Static files are are meant for js/css/images etc, that by definition are 'static' and won't change, but media files are for user-uploaded content.

提交回复
热议问题