[Django]-How to show current file in templates with Django FileFields

6👍

You didn’t look around well enough, the solution is a custom widget in contrib/admin/widgets.py, namely this one:

class AdminFileWidget(forms.FileInput):
    """
    A FileField Widget that shows its current value if it has one.
    """
    def __init__(self, attrs={}):
        super(AdminFileWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            output.append('%s <a target="_blank" href="%s">%s</a> <br />%s ' % \
                (_('Currently:'), value.url, value, _('Change:')))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

You can use this (or an adapted version) using the widgets meta option of ModelForms.

As far as I know your second problem shouldn’t be there at all, even without a nicer widget, let it know if it still persists after using a custom widget.

3👍

I don’t think beruic’s answer get enough attention as a comment, but he really got this since Django now fixes this automatically.

“A normal ClearableFileInput from Django.forms does it for me.”

See example below.

models.py

class PosterForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PosterForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Poster

        fields = ('title', 'img')

        widgets = {
            'img' : forms.ClearableFileInput(),
            'title' : forms.TextInput()
        }

0👍

I use this snippet to display ImageFields (with extra checkbox to delete them). Not sure how to display non image fields but maybe this snippet will give you some inspiration.

👤dzida

Leave a comment