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. Browser-native date input field by kytta 1 month, 1 week ago
  2. Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
  3. My firs Snippets by GutemaG 1 month, 2 weeks ago
  4. FileField having auto upload_to path by junaidmgithub 2 months, 3 weeks ago
  5. LazyPrimaryKeyRelatedField by LLyaudet 3 months ago

Comments

Please login first before commenting.