4

画像フィールドを持つモデルがあり、ModelForm を使用して画像を変更できるようにしたいと考えています。イメージを変更する場合は、古いイメージを削除して新しいイメージに置き換える必要があります。

次のように、ModelForm の clean メソッドでこれを実行しようとしました。

    def clean(self):
        cleaned_data = super(ModelForm, self).clean()

        old_profile_image = self.instance.image
        if old_profile_image:
            old_profile_image.delete(save=False)        
        return cleaned_data

これは、ユーザーが指定したファイルが正しくない場合 (たとえば、画像ではない場合) を除き、正常に機能します。その結果、新しい画像が保存されずに画像が削除されます。古いイメージを削除するのに最適な場所を教えてください。これは、古いイメージを削除する前に、新しいイメージが正しいことをどこで確認できるのでしょうか?

編集:可能であれば、ModelForm クラスでこれを行うことを好みます。

4

2 に答える 2

0

Ok I figured out how to do it in a clean way using a ModelForm. Basically I create a class called 'ChangeImageForm', which will make sure to delete the old image when changing an image. Furthermore it also works if an image is invalid:

class ChangeImageForm(ModelForm):

    def clean(self):
        cleaned_data = super(ModelForm, self).clean()
        self.old_image = self.instance.image
        return cleaned_data

    def save(self, commit=True):
        instance = super(ChangeImageForm, self).save(commit)

        if self.old_image:
            self.old_image.delete(save=False)

        return instance

Now I can easily add the above functionality to a ModelForm with an image field by inheriting from ChangeImageForm like this:

class MyModelForm(ChangeImageForm):
    class Meta:
        model = MyModel # model with an image field

I think overriding the ModelForm is the best place to do this, instead of in the Model class, since I only want to delete the old image in some cases.

于 2012-07-15T18:55:09.297 に答える
0

いくつかの答え:

ImageField は、アップロードされたファイルが Python Imaging Library を介して画像であることを検証する必要があります。そうでない場合、フォームは検証されません。

ImageField の path 属性には、古いファイルへのパスが必要です。

新しいイメージを保存した後、古いイメージを削除できます。ユーザーのファイル名入力をファイル名として使用しないでください。その方が安全で、同じファイル名をそのまま使用できます。その場合は、毎回古いファイルを上書きするだけで、削除手順を省略できます。

幸運を。

于 2012-07-10T21:21:40.607 に答える