ASML
ASML

Reputation: 199

Serve random image with Django

I have approx. 100.000 pictures and my goal is to generate a Django-powered webpage that displays one of those pictures at random every time the page loads (actually it's a bit more complicated, but that's my minimal example). My approach right now is as follows:

  1. I put all 100.000 files into the static folder of my app.
  2. I manually generate a database containing the paths to all images.
  3. A URL-associated view randomly selects a database entry (i.e., a path) and generates the page from a template.

My template for the view looks like this:

...
<body>
<H1>'Hello World' from the template!</H1>
Here's 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}} is the path to the random image. As you can see, I'm actually drawing the image to an HTML5 canvas with Javascript. Here's the corresponding Django view 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))

Although that actually works, I'm pretty sure that I'm violating some fundamental design principles. Is it good practice to serve static images this way? Or should I add the entire images (instead of just the paths) directly to the database, e.g., with an ImageField? What's the correct way of doing it?

Upvotes: 3

Views: 1864

Answers (1)

sepulchered
sepulchered

Reputation: 814

As commented ImageField doesn't actually store images in database, it has links to images in filesystem and generates proper url to image for it's use in templates.

You can get random image using rImage = Images.objects.order_by('?')[0] but keep in mind that it can be expensive and slow operation depending on database backend you're using (e.g. mysql). Then you can pass image object to template and use {{rImage.image_field.url}} (image field handles url generation for you, just set proper values in your project settings)

Upvotes: 2

Related Questions