Showing posts with label admin. Show all posts
Showing posts with label admin. Show all posts

Friday, 11 June 2010

Clearing FileFields in Django's admin

This post is as much a reminder for me as it will be helpful to others. Yesterday I added a couple of FileFields to a Django model, the point of them is to allow overriding of some site images. So the idea is that you can upload images or swf files to these fields, they'll replace the ones on the site, until you are bored of them then you can delete them and the original images will be restored.

After adding the FileFields to the model, they nicely appeared in the Django admin site. I uploaded an image, the override worked perfectly, now to restore the original image...

And that's where you hit a problem. There is no way in the Django admin to clear a FileField, you can replace it, but you can't clear it to NULL. Happily there is a workaround[1]. You first need to create a custom ModelForm for your model which includes an extra checkbox like so:

class MyCustomForm(ModelForm):
    clear_the_image = forms.BooleanField("Clear the image", required=False)

    class Meta:
        model = MyModel

    def save(self, commit=True):
        model_instance = super(MyCustomForm, self).save(commit=False)
        if self.cleaned_data.get('clear_the_image'):
            model_instance.the_file_field = None

        if commit:
            model_instance.save()

        return model_instance


Then in your MyModelAdmin class:

class MyModelAdmin(ModelAdmin):
    form = MyCustomForm


That's it. When you save the form, it will see if you asked to clear the image, if so it will set it to None and then save. Job done.

[1] Adapted from this: http://www.developerit.com/2010/04/17/django-admin-add-a-remove-file-field-for-image-or-filefields