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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.