Skip to content Skip to sidebar Skip to footer

Django File Upload - Hide The Currently Displayed Image Link In The Edit Template

I have a test template that allows a user to add an uploaded file image as well as the image title as a char field to the users account. This is working OK. I am now trying to allo

Solution 1:

To hide the currently displayed image link you can simply override get_context (below is the example for ClearableFileInput which is similar to FileInput).

It's very useful to check the source code when you're looking for solutions of this kind.

Django is an open source module, so you can look for the source code on GitHub: https://github.com/django/django/blob/main/django/forms/widgets.py

classClearableFileInputCustom(forms.ClearableFileInput):
    defget_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['is_initial'] = Falsereturn context

Solution 2:

I used this snippet in an old project. It's not great because you have to refresh the page/save the model, but it does what I think you want.

Widget:

classAdminImageWidget(forms.FileInput):                                    
    """A ImageField Widget for admin that shows a thumbnail."""def__init__(self, attrs={}):   # pylint: disable=E1002,W0102           super(AdminImageWidget, self).__init__(attrs)                       

    defrender(self, name, value, attrs=None):  # pylint: disable=E1002     
        output = []                                                         
        css = {'style': 'clear:left;float:left;margin:1em 1em 0 0;'}        
        output.append(super(AdminImageWidget, self).render(name, value,     
                                                           attrs=css))      
        if value andhasattr(value, "url"):                                 
            output.append(('<a target="_blank" href="%s">''<img src="%s" alt="" ''style="float:left;border:1px solid black;" /></a> '
                           % (value.url, value.url)))                       
        return mark_safe(u''.join(output)) 

To use it in the admin:

classSomeAdminForm(forms.ModelForm):
    classMeta:
        model = MyModelwidgets= {
            'my_image_field_name': AdminImageWidget(),
        }

classSomeAdmin(admin.ModelAdmin):
    form = SomeAdminForm

Solution 3:

You will have to set the src attribute of the img tag in your template in order to display the image successfully.

<imgsrc="{{attachment_details.file_url}}"/>

{{attachment_details.file_url}} of course has to be replaced with however you are retrieving your file url.

Post a Comment for "Django File Upload - Hide The Currently Displayed Image Link In The Edit Template"