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

 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. Honeypot Field by SmileyChris 4 years, 10 months ago
  2. Custom model field to store dict object in database by rudyryk 1 year, 10 months ago
  3. Modifying the fields of a third/existing model class by marinho 1 year, 1 month ago
  4. custom css classes for newforms by robharvey 4 years, 9 months ago
  5. PreSaveMiddleware by pterk 4 years, 2 months ago

Comments

(Forgotten your password?)