Dan
Dan

Reputation: 13210

How to tell if user changed file in django ModelForm

I have a django ModelForm with an image field. I want to resize the image when the user submits the form, but only if they uploaded a new image. My code looks like this:

class EditProfileForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['picture', '...']

    def clean_picture(self):
        picture = self.cleaned_data['picture']
        if picture.file: #This isn't right though
            #resize it
        return picture

However it seems like picture.file always exists if the model being edited contains a file. I know I can check request.FILES back in the view, but that's very inelegant. Is there a better way?

Upvotes: 0

Views: 140

Answers (2)

SuperNova
SuperNova

Reputation: 27486

In js,

  • In JS, set a global variable file_changed = 0.
  • HTML input tag < input ng-model="avatar" type="file" onchange="ChangeFile()">
  • Lets say ChangeFile() will provide a small preview of the file to be uploaded
  • In function ChangeFile set file_changed=1 once the file is selected.

Upvotes: 0

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

In general, you can do this with self.changed_data, which returns a list of the names of the fields where the value changed. Whether there's anything special about a FileField that would interfere I don't know offhand.

Upvotes: 1

Related Questions