views:

38

answers:

2

Hi,

I'm looking to the best way to overriding the _get_url method from ImageField, I need to customize the url since I don't want the default returned url (I distribute this image trhough a view to manage ACL on it so the url based on the MEDIA_ROOT is wrong).

Should I have to create my own ImageField ? or is there a solution using less code ?

Thanks in advance Fabien

+1  A: 

The url returned be _get_url is actually generated by the used Storage class; it would probably make more sense to create your own Storage and use it when creating the ImageField! See: http://docs.djangoproject.com/en/dev/topics/files/#file-storage, http://docs.djangoproject.com/en/dev/howto/custom-file-storage/

You will neet to override the Storage.url method for that!

lazerscience
I was thinking the url was managed by the model. Now, it makes sense, thank you :)
Fabien Engels
A: 

Thanks to lazerscience, here my final solution :

from django.core.files.storage import FileSystemStorage
from django.db.models import get_model
from django.core.urlresolvers import reverse
from django.db import models
from django.conf import settings


class PhotographerStorage(FileSystemStorage):
    def __init__(self, location=None):
        super(PhotographerStorage, self).__init__(location)

    def url(self, name):
        photo_model = get_model('photographer', 'photo')
        photo = photo_model.objects.get(original_image=name)
        url = super(PhotographerStorage, self).url(name)
        return '%s?size=%d' % (reverse('photographer_photo_display',
            args=[photo.slug]), 300)


fs = PhotographerStorage(location=settings.PHOTOGRAPHER_LOCATION)

class Photo(models.Model):
    ...
    original_image = models.ImageField(storage=fs)
    ...

It works like a charm :)

Fabien Engels