Skip to content

Instantly share code, notes, and snippets.

@berinhard
Created June 14, 2016 16:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berinhard/1acee161da786fa09279b22dbd1c2cca to your computer and use it in GitHub Desktop.
Save berinhard/1acee161da786fa09279b22dbd1c2cca to your computer and use it in GitHub Desktop.
This gist show a solution that I've figured out to open all documents links on model object detail page of Django's admin on a new tab.
class NewTabAdminFileWidget(AdminFileWidget):
"""
This widget is an extensions from AdminFileWidget which is used with all
ImageFields and FileFields at admin forms. This widget follows the api defined
by django.forms.widgets.ClearableFileInput widget.
"""
def __init__(self, *args, **kwargs):
super(NewTabAdminFileWidget, self).__init__(*args, **kwargs)
template_with_initial_new_tab = (
'%(initial_text)s: <a href="%(initial_url)s" target="_blank">%(initial)s</a> '
'%(clear_template)s<br />%(input_text)s: %(input)s'
)
self.template_with_initial = ('<p class="file-upload">%s</p>' % template_with_initial_new_tab)
class YourModelAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
"""
Changes widget of FileFields to open documents on new tab
"""
super(YourModelrAdminForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
if isinstance(field, forms.FileField):
field.widget = NewTabAdminFileWidget()
class Meta:
model = YourModel
exclude = []
@mazulo
Copy link

mazulo commented Jun 15, 2016

Is there a particular reason to use string interpolation? (line 14)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment