2

I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source.

ie. Instead of declaring form fields like this...

            {{ form.first_name }}   

.. I actually do ...

            <label for="id_first_name">Your name:</label>
            <input type="text" value="{{  form.first_name.somehow_get_initial_value_here }}" name="first_name" id="id_first_name" class="blabla" maxlength="30" >
            {% if form.first_name.errors %}<span>*** {{ form.first_name.errors|join:", " }}</span>{% endif %}

Problem is that there seems to be no way to get the initial value of the field in the second method. {{ form.first_name }} statement does render the input element with the proper initial value but somehow there is nothing like {{ form.first_name.initial_value }} field when you want to render the form manually.

utku_karatas
  • 6,163
  • 4
  • 40
  • 52
  • The input tag has a `value` attribute. ` ` for example. Is that what you need? – JoshD Oct 14 '10 at 03:51
  • Thanks but that initial value comes from the server side, dynamically. Edited the code sample to be more clear. – utku_karatas Oct 14 '10 at 03:56
  • If you provided `first_name` in the `initial` dict when creating the form class instance, the value will automatically be provided in `{{ form.first_name }}` the first time the form is displayed. – André Caron Oct 14 '10 at 04:30
  • if the only issue is to put styles you can add the css classes in the form fields in your code. – Ankit Jaiswal Oct 14 '10 at 09:42
  • Take a look here: http://stackoverflow.com/questions/604266/django-set-default-form-values/604325#604325 – OmerGertel Oct 14 '10 at 10:35

2 Answers2

4

There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need:

http://code.djangoproject.com/ticket/10427

Harold
  • 5,147
  • 1
  • 19
  • 15
0
<input value="{{form.name.data|default_if_none:'my_defaut_value'}}" ... />

You will have to use default_if_none because the implicit value of a bound field will not be stored in data. More details here

Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108
  • Maybe I missed something but "form.field.data" comes up None everytime. – utku_karatas Oct 17 '10 at 19:38
  • Yeah, I see now that it raises some issues also on my side. It works when the form comes in error mode tho :P . But, as at the end of my answer and as the first guy responded, more details (if you have the nerv and tme to read the full ticket) are found in that ticket ;) – Nicu Surdu Oct 21 '10 at 14:45