Skip to content

Instantly share code, notes, and snippets.

@arruda
Created February 6, 2012 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arruda/1754686 to your computer and use it in GitHub Desktop.
Save arruda/1754686 to your computer and use it in GitHub Desktop.
Adicionando um widget no seu formfield, usando inlineformset_factory
from django.db import models
def my_nice_formfield_callback(f):
formfield = f.formfield()
if isinstance(f, models.FileField):
formfield.widget = NoFullPathLinkFileInput()
return formfield
from somepath.my_formfield_utils.py import my_nice_formfield_callback
def my_view(request):
...Some code...
MyModelInlineFormSet = inlineformset_factory(MyModel, MyInlineModel,formfield_callback=my_nice_formfield_callback)
....Some code...
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.forms.widgets import ClearableFileInput
class NoFullPathLinkFileInput(ClearableFileInput):
"new widget that removes the link and full path from a uploaded file, for security"
def render(self, name, value, attrs=None):
substitutions = {
'initial_text': self.initial_text,
'input_text': self.input_text,
'clear_template': '',
'clear_checkbox_label': self.clear_checkbox_label,
}
template = u'%(input)s'
substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
if value and hasattr(value, "url"):
value_new = force_unicode(value).split('/')[-1]
template = self.template_with_initial
substitutions['initial'] = (u'%s' % escape(value_new))
return mark_safe(template % substitutions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment