I am new to web development and I am working on a basic image gallery application (training exercise) using Django. I set it up so that I could upload a zip full of images right away to create a new album. Everything seems to be working fine, but I get an HTTP 504 error when the downloaded file is especially large.
I'm going to (please correct me if I am wrong) this error means that my application is too slow to return an HTTP response. I assume that this is due to the fact that it takes a lot of time to unpack and process (create a Pic object in the database and create thumbnails) of all images.
Is there a way to return a response (say, to some intermediate page) while still doing the processing in the background - perhaps using threads? What is the right way to handle this? Is it time to start learning Javascript / AJAX?
Thanks!
Model:
from django.db import models from blog.models import Post class Album(models.Model): title = models.CharField(max_length=128) slug = models.SlugField() description = models.TextField() parent = models.ForeignKey('self', null=True, blank=True) pub = models.BooleanField() date_created = models.DateTimeField(auto_now_add=True) date_published = models.DateTimeField(null=True, blank=True) date_modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.title class Pic(models.Model): image = models.ImageField(upload_to='pics/%Y/%m') title = models.CharField(max_length=128) caption = models.TextField(blank=True, null=True) albums = models.ManyToManyField('Album', null=True, blank=True) posts = models.ManyToManyField(Post, blank=True, null=True) date_taken = models.DateTimeField(null=True, blank=True) date_uploaded = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.title
View:
I do this manually because I did not start the Django admin when I started. I think it would be better to use the admin setting here.
def new_album(request): if request.method == "POST": form = AlbumForm(request.POST, request.FILES) if form.is_valid(): from gallery.pic_handlers import handle_uploaded_album pics = handle_uploaded_album(request.FILES['pic_archive']) a = form.save() a.slug = slugify(a.title) a.save() for pic in pics: pic.albums.add(a) return HttpResponseRedirect('/gallery/album/%s/' % a.slug) else: form = AlbumForm() return render_to_response('new_album.html', { 'form' : form, }, context_instance = RequestContext(request))
Additional processing:
def handle_uploaded_album(pic_archive): destination = open(join(settings.MEDIA_ROOT,pic_archive.name), 'wb+') for chunk in pic_archive.chunks(): destination.write(chunk) destination.close() today = datetime.date.today() save_path = 'pics/{0}/{1:02}/'.format(today.year, today.month) tmp_path = 'tmp/' z = zipfile.ZipFile(join(settings.MEDIA_ROOT,pic_archive.name), 'r') pics = [] for member in z.namelist(): if '/' in member or '\\' in member: