Rendering a value as text instead of field inside a Django Form
Also, don't forget you can also do {{myform.instance.name}}
Old topic, but I think some people still comes here.
You can do something like this too:
from django.utils.safestring import mark_safe
class PlainTextWidget(forms.Widget):
def render(self, _name, value, _attrs):
return mark_safe(value) if value is not None else '-'
And in your form
class SomeForm(Form):
somename = forms.CharField(widget=PlainTextWidget)
Under Django 2.1+ you'll need the following:
from django.utils.safestring import mark_safe
class PlainTextWidget(forms.Widget):
def render(self, name, value, attrs=None, renderer=None):
return mark_safe(value) if value is not None else '-'
You can also use a new widget: I did this so that I could have a widget that created a text display of a date, and a hidden form with the same date in it, so it could be visible to the user, but they cannot change it.
Here is an initial (still testing/to be cleaned up) version:
class DayLabelWidget(forms.Widget):
def render(self, name, value, attrs):
final_attrs = self.build_attrs(attrs, name=name)
if hasattr(self, 'initial'):
value = self.initial
if type(value) == type(u''):
value = datetime.date(*map(int, value.split('-')))
return mark_safe(
"%s" % value.strftime("%A (%d %b %Y)")
) + mark_safe(
"<input type='hidden' name='%s' value='%s' />" % (
name, value
)
)
def _has_changed(self, initial, data):
return False
You then use this in the field as (widget=DayLabelWidget,)
.
<form>
{% for field in form %}
{{ field.label }}: {{ field.value }}
{% endfor %}
</form>
Take a look here Form fields and Working with forms