Add a "remove file" field for Image- or FileFields

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    the_file = models.FileField(
        upload_to="file/path",
        blank=True)
    remove_the_file = models.BooleanField()

    def save(self):
        if self.remove_the_file:
            self.the_file = ""
            self.remove_the_file = False
        super(ModelName, self).save()

Comments

jerry2801 (on October 21, 2009):

is a good idea~

#

rfugger (on November 3, 2009):

This is simple and nice. I prefer to not add an extra database column when it's not needed, though. You can just create a custom ModelForm for your model, with the following:

remove_the_file = forms.BooleanField(required=False)

def save(self, *args, **kwargs):
    object = super(self.__class__, self).save(*args, **kwargs)
    if self.cleaned_data.get('remove_the_file'):
        object.the_file = ''
    return object

Use that form in your ModelAdmin, and there's no need to change the database.

Thanks for the idea!

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.