Django File Upload - Hide The Currently Displayed Image Link In The Edit Template
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
class ClearableFileInputCustom(forms.ClearableFileInput):
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context['widget']['is_initial'] = False
return 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:
class AdminImageWidget(forms.FileInput):
"""A ImageField Widget for admin that shows a thumbnail."""
def __init__(self, attrs={}): # pylint: disable=E1002,W0102
super(AdminImageWidget, self).__init__(attrs)
def render(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 and hasattr(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:
class SomeAdminForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'my_image_field_name': AdminImageWidget(),
}
class SomeAdmin(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.
<img src="{{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"