ShowOnly widget for froms

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class ShowOnly(forms.Widget):
    """
    Show only the data do NOT have a input field
    """
    input_type = 'hidden'

    def render(self, name, value, attrs=None):
        from django.utils.safestring import mark_safe
        from django.utils.encoding import force_unicode
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            value = force_unicode(value)
            final_attrs['value'] = force_unicode(value)
        return mark_safe(u'<input%s />%s' % (forms.util.flatatt(final_attrs),value))


# Example usage:
class SomeForm(forms.Form):
    justShowThis = forms.CharField(required = False, widget = ShowOnly(), initial = 'Input (not editable)', label = 'My nice Label')

More like this

  1. Tamper safe HiddenFields by alexmeisel 4 years, 6 months ago
  2. DefaultValueWidget by miracle2k 5 years, 10 months ago
  3. Currency Fields with newforms by sago 6 years, 1 month ago
  4. Sign a string using SHA1, then shrink it using url-safe base65 by simon 4 years, 8 months ago
  5. tag: render form field by crucialfelix2 3 years, 5 months ago

Comments

brooks_lt (on November 13, 2008):

I may be missing something, but how does the form pass back the value for the field? Even in conjunction with 1184.

#

alexmeisel (on January 1, 2009):

Uploaded the wrong code ... Sorry about that, here is the correct version.

#

pnm (on March 25, 2009):

FWIW a slight modification which shows a different text (useful for lookup values), while retaining the field value in the hidden field. Used with http://www.djangosnippets.org/snippets/916/ it can be dynamically changed if the form instance is initiated with a model instance.

Pretty basic stuff, but it took a while to figure out what was accessible where.

class ShowOnly(Input): """ Show only the data do NOT have a input field """ input_type = 'hidden'

def render(self, name, value, attrs=None):
    from django.utils.safestring import mark_safe
    from django.utils.encoding import force_unicode
    if value is None: 
        value = ''
    final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
    if final_attrs.get('showtext') :
        showtext = final_attrs.get('showtext')
        del final_attrs['showtext']
    else :
        showtext = value
    showtext=force_unicode(showtext)
    if value != '':
        # Only add the 'value' attribute if a value is non-empty.
        value = force_unicode(value)
        final_attrs['value'] = force_unicode(value)
    return mark_safe(u'<input%s />%s' % (flatatt(final_attrs),showtext))

#

(Forgotten your password?)