Skip to content
Advertisement

Is it possible to remove ‘Currently’ label when using django-stdimage?

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement