显示目录Django中的所有图像 [英] displaying all images from directory Django

查看:49
本文介绍了显示目录Django中的所有图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何将目录中的图像显示到页面上。我正在尝试创建一个图库应用。我正在尝试一点一点地做到这一点。我的目标是为相册创建缩略图(照片的第一张图像)。单击相册后,应显示所有图像。我认为这将通过AJAX请求完成。不太确定,因为我是Web开发的新手。我需要一些帮助来设置它。

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 thumbnail (first image of photos) for the album. When the album is clicked, all the images should be displayed. I think this would be done with an AJAX request. Not quite sure as I am new to web development. I need some help setting this up.

图像结构:

/gallery
   /static
      /images
         /album1
            img1
         /album2
            img2
         ...etc

我不确定如何在我的views.py中获取这些图像并将其显示在html页面上。

I'm not sure how to get these images in my views.py and display them on an html page.

这是我想出的models.py,但可能需要更多工作:

Here is the models.py I came up with but probably needs more work:

class Album(models.Model):
    title = models.CharField(max_length = 60)
    def __unicode__(self):
        return self.title

class Image(models.Model):
    title = models.CharField(max_length = 60, blank = True, null = True)
    tags = models.ManyToManyField(Tag, blank = True)
    albums = models.ManyToManyField(Album, blank = True)
    width = models.IntegerField(blank = True, null = True)
    height = models.IntegerField(blank = True, null = True)

我觉得我可能缺少Image类中的某些内容,例如 ImageField FileField ,但我是手动将文件放在目录中,所以不确定是否需要。

I feel I might be missing some things in my Image class such as ImageField or FileField but I am putting the files in the directory manually so I'm not sure if there are required.

推荐答案

在此阶段,不可能完全回答您的问题,但让我们看看。

At this stage it is not quite possible to answer your questions in a whole, but let's see.

A:目录和文件组织

目前尚不清楚目录结构与模型的相似之处

It isn't clear yet how your directory structure resembles your models.

您的图像与相册之间存在N:M关系。到目前为止还可以。
令人困惑的是您的图片结构。

Your images have a N:M Relationship with albums. That is ok so far. What's confusing is your structure of images.

结构看起来像图像和相册的1:1关系。
如果一个图像属于多个相册,是否会导致文件重复?

The structure looks like a 1:1 Relationship of images and albums. Does this result in duplicate files if an image belongs to multiple albums?

因此,您需要首先解决的一件事:如何在硬盘上组织图像?

So one thing you need to solve first: How are images organized on your hard drive?

B:查找文件并从中创建URL

现在我们需要寻找找到图像文件路径的方法。我们假设您的文件与django应用程序位于同一台计算机上,因此我们可以使用本地路径。如果您的图片位于AWS之类的其他位置,则需要提供一种不同的机制来获取图片网址。

Now we need to find a way to find the path to your image files. We assume, your files reside on the same machine as your django application, so we can use local paths. If your pictures were in a different location like AWS, you would be required to provide a different mechanism to get the picture url.

对图片进行整理后就可以编写您的图像模型检索图像路径的模型方法。
一个简单的方法是,标题是唯一字段,并且确实等于图像文件名,该文件名也必须是唯一的。我向您保证,这仅适用于哈希文件名或非常奇怪的文件名约定,当您将文件上传到图库时,这些约定必须由您自己决定。当然,还有其他选择可以确保您获得正确的文件,但是让我们保持简单,只是要牢记一点。

Once you have sorted it out you can write a model method for your image model to retrieve the image path. A trivial approach would be that your title is a unique field and does equal your image file name, which had to be unique as well. I'll promise you, this will only work with hashed filenames or very strange filename conventions you had to make up on your own when files are uploaded to your gallery. Of course there are other options to ensure you get the right file, but let's keep things simple, just something to keep in mind.

C:一些示例代码

好的,让我们写一些代码。这只是一个人为的例子,它想解释基本思想。有关目录遍历的更多信息,可以在这里找到:
在Python中寻找类似于Java的文件遍历功能

Alright, let's write some code. This is just a contrived example, that wants to explain the basic idea. Some more information about directory traversal can be found here: Looking for File Traversal Functions in Python that are Like Java's

#models.py

import os
from os.path import join

class Image(models.Model):

def get_image_path(self):
    for root, dirs, files in os.walk('<parents of gallery>/gallery/static/images/<album_if_required>'):
       #debug information, just to get an idea how walk works.
       #currently we are traversing over all files with any extension
       print "Current directory", root
       print "Sub directories", dirs
       print "Files", files

       for file in files:
        if file.startswith(self.title):
            #now we have found the desired file.
            #value of file: "myimagetitle.jpg" <-- no path info
            #value of root: "/home/yourhome/gallery/static/images/myalbum"
            #we want to use this information to create a url based on our static path, so we need only the path sections past "static"
            #we can achieve this like so (just one way)
            mypath = os.sep.join(os.path.join(root, file).split(os.sep)[4:])

            #yields: /images/myalbum/myimagetitle.jpg

            return mypath

很棒,现在我们可以在模板中使用静态路径了

great, now we have a path we can use in our template with static as base.

#template.html
<!-- fancy html stuff goes here -->
<img src="{static myimage.get_image_path}">
<!-- more html -->

D:代码说明

我认为这段代码的某些部分需要解释。

I think some parts of this code require explanation.

os.walk是一个生成器方法,它将遍历您传递给它的路径。它将把路径返回到它查找的当前节点(根),以及您可以在下面找到的子目录(目录)和文件(文件)。您可以从树中删除节点或节点模式,因此可以对某些对象进行过滤。

os.walk is a generator method that will traverse the path you pass to it. It will return the path to the current node it looks at (root) and what subdirectories (dirs) and files (files) you can find underneath. You can remove nodes or node pattern from the tree, hence you can filter on certain objects. But this would go to far right now.

一旦找到文件候选者,我们需要构建一个可在应用程序中使用的路径。 HTML模板无法使用文件的物理位置,因此我们需要将其转换为URL。您将必须知道您的url方案是什么样的。我假设您依赖静态文件夹。

Once we have found a candidate for our file, we need to build a path we can use in our application. The HTML template can't use the physical location of the file, so we need to transform it into a URL. You will have to know what your url scheme will be like. I assumed you rely on static folders.

URL创建在这里发生:

URL creation happens here:

os.sep.join(os.path.join(root, file).split(os.sep)[4:])

让我们看一下它的部分内容:

let's look at it in parts:


  1. os.path .join(root,file)#加入根路径和一个长字符串的文件名

  1. os.path.join(root, file) #join the root path and the file name for one long string

.split(os.sep)[4:] #获取路径的子字符串。我们用目录分隔符char分隔路径,该分隔符是os依赖的。这将返回一个列表。我们只需要静态部分下的元素,在我的示例中,这导致列表的元素4

.split(os.sep)[4:] #get the substring of the path. We split the path by the directory separator char which is os dependent. This will return a list. We only want the elements under the "static" part, in my example this resulted in element 4 of the list

os.sep .join(...)#最后但并非最不重要的一点是,我们必须再次构建一个字符串。因此,我们将所有列表元素与目录分隔符连接在一起,生成'/images/myalbum/myimagetitle.jpg'

os.sep.join(...) # last but not least we have to build a string again. So we join all list elements with the directory separator, yielding '/images/myalbum/myimagetitle.jpg'

如您所见,这只是实现所需目标的一种可能方法。如果您提供有关文件组织方式的更多信息,我相信我们可以找到更好的方法。请不要上面的代码还没准备好投入生产!

So as you can see, this is just one possible way to achieve what you want. If you provide more information about how your files are organized, I'm sure we can find a much better way. Please not the code above is not ready for production!

这篇关于显示目录Django中的所有图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆