Login

Field value as plain text which can't be edited by user

Author:
szczavv
Posted:
September 29, 2009
Language:
Python
Version:
1.1
Tags:
forms hidden widget input
Score:
0 (after 0 ratings)

Shows field value as plain text which can't be edited by user. Field value (or key value for foreign keys) is stored in hiddden input.

Value of field is stored in hidden input and current value is placed as plain text. User can't change it's value. If field is foreign key then additional attribute 'key' should be set to True (key is stored in hidden field and unicode value is visible): self.fields['my_field'].widget = HiddenInputWithText(attrs={ 'key' : True }) There is one condition: for foreign key field its name have to be same as lowercased model name.

Default 'key' value - False is correct for non-foreign key fields: self.fields['my_field'].widget = HiddenInputWithText()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django import forms
from django.utils.safestring import mark_safe
from django.db.models.loading import get_model

class HiddenInputWithText(forms.TextInput):
    input_type = 'hidden'

    def __init__(self, *args, **kwargs):
        super(HiddenInputWithText, self).__init__(*args, **kwargs)
        self.attrs = kwargs.get('attrs', {})
        self.key = self.attrs.get('key', False)
        
    def render(self, name, value, *args, **kwargs):
        model = get_model('YOUR_APP_NAME', name)
        if self.key:
            text = unicode(model.objects.get(pk=value)) if value is not None and value != '' else '-----'
        else:
            text = value
        html = '%s %s' % (super(HiddenInputWithText, self).render(name, value, self.attrs), text)
        return mark_safe(html)

More like this

  1. Tamper safe HiddenFields by alexmeisel 6 years, 3 months ago
  2. Honeypot Field by SmileyChris 7 years, 11 months ago
  3. custom css classes for newforms by robharvey 7 years, 9 months ago
  4. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 4 months ago
  5. Dynamically change a form select widget to a hidden widget by epicserve 5 years, 8 months ago

Comments

Please login first before commenting.