views:

861

answers:

5

Is there a simple way to make Django render {{myform.name}} as

John Smith

instead of

<input id="id_name" name="name" value="John Smith" />

inside <form> tags? Or am I going about this the wrong way?

+7  A: 
<form>
    {% for field in form %}
            {{ field.label }}: {{ field.initial }}
    {% endfor %}
</form>

Take a look here Form fields and Working with forms

zdmytriv
Thanks - I had seen .label but not .initial. Curiously, .initial isn't even mentioned in the "Working with forms" document.
amdfan
.initial only works the first time the form is presented, right? For example, if there are errors and you re-present the form, there will be no initial in my experience.
dfrankow
In Django terminology, this only works with unbound forms. What if you want it to work with both unbound and bound forms?
dfrankow
+2  A: 

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,).

Matthew Schinckel
+1  A: 

Also, don't forget you can also do {{myform.instance.name}}

nbv4
what is this? where is it documented?
dfrankow
form.instance returns the object that the bound form is representing. It's in the docs here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method I should also mention that this only works with modelforms
nbv4
ah, google app engine does not support ModelForm, so we're using Form.
dfrankow
+1  A: 

Why not use {{ field.data }} ?

alj
+1  A: 

I think this is what you want: http://code.djangoproject.com/ticket/10427

I patched my django and voila...

Trunet