Задать вопрос

Тел: +7 965 3737 888

512

Просмотров

6

Ответов

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

This adds a checkbox in the admin site that removes the reference to a file uploaded via a FileField (or ImageField). It does not delete the actual file.

Вопрос полезен? Да0/Нет0
file_4748.py(300.0б)
None

Ответы (6):

Ответmachrider:25.10.2011
Ответ полезен? Да0/Нет0

Just to clarify sdeleon28's comment:

The blank=True, null=True feature was added in Django 1.3. FileFields now use a ClearableFileInput widget (added in 1.3) by default. If you're on Django 1.2 or earlier, you'll still need to do some customization yourself.

Ответsdeleon28:19.10.2011
Ответ полезен? Да0/Нет0

"Optimally, I would prefer to have the checkbox next to the file form field itself."

This is default behavior when the FileField is set as optional in the model.

The trick is to set both blank=True, null=True.

Don't use the snippet, define the model correctly! ;) Hope this helps.

Ответmhulse:20.05.2011
Ответ полезен? Да0/Нет0

Just FYI for those thinking about using code mentioned here...

This adds a checkbox to the model, in the admin, at the bottom of the form. This may not be optimal if you have multiple file fields in your model.

Optimally, I would prefer to have the checkbox next to the file form field itself.

Ответhede:27.11.2010
Ответ полезен? Да0/Нет0

Seems something has changed. There's some "commit" parameter. If it's set, above things do not work here. Btw: I cannot use self.__class__ here neither. For me the following works (SectionModelForm is the ModelForm class):

remove_file = forms.BooleanField(required=False)
def save(self, commit=False, *args, **kwargs):
  obj = super(SectionModelForm, self).save(commit=False, *args, **kwargs)
  if self.cleaned_data.get('remove_file'):
    obj.file = ''
  if commit:
    obj.save()
  return obj

Ответrfugger:03.11.2009
Ответ полезен? Да0/Нет0

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!

Ответjerry2801:21.10.2009
Ответ полезен? Да0/Нет0

is a good idea~