How To Assign A Value To A Django Form Field In The Template?
Solution 1:
you do it in Python, which can then be available to the HTML form or generator
in forms.py
you can set the initial
property to define the default value of the field.
ex: name = forms.CharField(initial='class')
or dynamically in views.py
you can use a dict
.
ex: f = CommentForm(initial={'name': 'instance'})
Once available within the form
instance you can use {{ form.field.value }}
in your HTML or automatically with a generator
Extended reference: https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values
Solution 2:
You could render the form out manually field by field but then render all other fields using Django template interpolation, but your hidden field you can render manually. e.g.
{% for thing in things %}
<p> {{ thing.content }} </p><!-- Reply form --><formFORM_PARAMS_HERE ><divclass="form-row">
{{ form.other_form_field.errors }}
{{ form.other_form_field.label_tag }} {{ form.other_form_field }}
</div>
... (more form rows)
<divclass="form-row"><inputtype="hidden"name="replyingto"id="replyingto_id"value="{{ thing.number }}"><inputtype="text"label="Reply"></input></div></form>
{% endfor %}
I faced this exact problem and was finally able to resolve it as I think you want after finding this excellent and hard to find reference on it.
Post a Comment for "How To Assign A Value To A Django Form Field In The Template?"