Overriding _get_url () from ImageField

I am looking for the best way to override the _get_url method from ImageField, I need to configure the URL since I do not want the default URL (I distribute this image, but see how to manage the ACL on it, so the url is based on MEDIA_ROOT mistakenly).

Should I create my own ImageField? or is there a solution that uses less code?

Thanks in advance Fabien

+3
source share
2 answers

The returned URL will _get_urlactually be generated by the Storage class used; it probably makes sense to create your own repository and use it when creating ImageField! See: http://docs.djangoproject.com/en/dev/topics/files/#file-storage , http://docs.djangoproject.com/en/dev/howto/custom-file-storage/

You can override the method Storage.urlfor this!

+6
source

Thanks to lazerscience, here is 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 :)

+4
source

Source: https://habr.com/ru/post/1753280/


All Articles