2

I am using django-stdimage in my Django app and it works great, the only problem is that I want to remove the 'Currently' string, the clear checkbox and the rest of the decoration from the HTML template. I can't figure out how to achieve this.

Here is the StdImageField declaration inside my models.py:

photo = StdImageField(upload_to=join('img', 'agents'),
                      variations={'thumbnail': (100, 100, True)}, default=None,
                      null=True, blank=True, )

I have read several SO answer about modifying the ImageField widget to use the class ClearableFileInput but it seems that the widget attribute is not allowed as a StdImageField class parameter.

Is there a way to remove all this decoration?

Thank you.

juankysmith
  • 11,839
  • 5
  • 37
  • 62
  • Remove where? in forms? in the admin? – Udi Jan 19 '17 at 22:22
  • remove/hide them In the HTML template. I suppose I have to make some modifications in models.py or forms.py – juankysmith Jan 20 '17 at 07:01
  • @juankysmith I might be wrong, but it seems that `StdImageField` operates only at models level. Can't you use `ImageField` with custom widget in your forms.py and `StdImageField` in your models.py? – mateuszb Feb 13 '17 at 21:51

1 Answers1

9

The StdImageField extends Django's ImageField

Django's ImageField defines 'form_class': forms.ImageField

and Django's forms.ImageField default widget is: ClearableFileInput

So if you want to change this widget on a model.fields level, you need to extend StdImageField and override the formfield method to return a form_class with a form.field having another default widget.

A simple example solution should look like this:

class NotClearableImageField(forms.ImageField):
    widget = forms.FileInput


class MyStdImageField(StdImageField):
    def formfield(self, **kwargs):
        kwargs.update({'form_class': NotClearableImageField})
        return super(MyStdImageField, self).formfield(**defaults)

# Now you can use MyStdImageField
# in your model instead of StdImageField
class MyModel(models.Model):
    my_image = MyStdImageField(*args, **kwargs)

but this will be a change affecting all ModelForm's extending your Model (including the Django admin).

You maybe don't want to do that, what you can do instead is to apply this widget override only on a single form where you want this specific behavior. ModelForms already support this:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
            'my_image': forms.FileInput(),
        }

Now you can use this form class on the places where you want the change.

Todor
  • 15,307
  • 5
  • 55
  • 62