开发者

Django - Post process image after upload with dynamic parameters

I want to give the user the ability to post process an uploaded image using user defined parameters (width, height, compression etc.)

I want to manipulate the image in a pre_save signal:

class Media(models.Model):
    id = models.AutoField(primary_key=True)
    file = models.FileField(upload_to='uploads/%m-%Y/')
    content_type = models.CharField(max_length=100, blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True, editable=Fals开发者_开发百科e)

class MediaForm(ModelForm):
    class Meta:
        model = Media

    def save(self, force_insert=False, force_update=False, commit=True):
        m = super(MediaForm, self).save(commit=False)
        m.content_type = self.cleaned_data['file'].content_type
        if commit:
            m.save()

def handle_uploaded_media(sender, instance, *args, **kwards):
    # Use PIL to process media here (depending on type)

models.signals.pre_save.connect(handle_uploaded_media, sender=Media)

The problem I have is that I am unable to pass parameters to the pre_save handler from the form save method. What I'd like is to be able to do something like this:

if request.method == 'POST':
    form = MediaForm(request.POST, request.FILES)
    if form.is_valid():
        form.save({'width':500, 'height':500, 'compression':60})

Because it's neat and tidy and I can obviously replace the save arguments with user defined values. Is this possible? Is there a better way to do it?


I think in this case, you're pretty much going to have to either put handle_uploaded_media() in your form.save(), or call it from form.save() in order to be able to pass in the user-provided values.

You don't really gain anything by calling handle_uploaded_media() from a signal, other than complicating the passing of values from your form to it. if it's a separate method you're calling from form.save, you can still share it with other models/methods, etc.

My $0.02

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜