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
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 week ago
- Help text hyperlinks by sa2812 1 month ago
- Stuff by NixonDash 3 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago
Comments
Please login first before commenting.