Login

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

Author:
szczavv
Posted:
September 29, 2009
Language:
Python
Version:
1.1
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. "Magic Link" Management Command by webology 4 months, 1 week ago
  2. Closest ORM models to a latitude/longitude point by simonw 4 months, 1 week ago
  3. Log the time taken to execute each DB query by kennyx46 4 months, 1 week ago
  4. django database snippet by ItsRLuo 4 months, 2 weeks ago
  5. Serialize a model instance by chriswedgwood 5 months, 2 weeks ago

Comments

Please login first before commenting.