Serve randomly with Django

I have approx. 100,000 images, and my goal is to create a web page with Django that displays one of these images randomly every time the page is loaded (actually a little more complicated, but my minimal example). My approach right now looks like this:

  • I put all 100.000 files in a static folder of my application.
  • I am manually creating a database containing paths to all images.
  • The linked URL randomly selects a database entry (i.e. path) and generates a page from the template.

My template for the view looks like this:

...
<body>
<H1>'Hello World' from the template!</H1>
Here a random image: "{{rImage}}"<p>
<canvas class="stream" id="canvas" style="z-index: 1; outline: 1px solid red;" width=505px height=336px></canvas>
<script>
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");

img = new Image();
img.onload = function(){};
img.src = "/static/rim/{{rImage}}";

cxt.drawImage(img,0,0,canvas.width,canvas.height);
</script>
</body>
...

      

{{rImage}} - path to a random image. As you can see, I am actually drawing an image to an HTML5 canvas using Javascript. Here's the relevant Django representation in Python:

def index(request):
    rImage = Images.objects.all()[random.randint(0, 100000)].relativeUrl
    template = loader.get_template('rim/index.html')
    context = RequestContext(request,{'rImage':rImage})
    return HttpResponse(template.render(context))

      

While this does work, I'm sure I'm breaking some fundamental design principles. Is it good to use static images this way? Or should I add all images (not just paths) directly to the database, for example using ImageField? What's the correct way to do this?

+3


source to share


1 answer


As noted, ImageField

it does not actually store images in the database, it has links to images in the file system and generates the correct URL for the image used in templates.



You can get a random image with rImage = Images.objects.order_by('?')[0]

, but keep in mind that this can be expensive and slow depending on the database backend you are using (e.g. mysql). Then you can pass the image object to the template and use {{rImage.image_field.url}}

(the image field handles the url generation for you, just set the correct values ​​in your project settings)

+1


source







All Articles