Tato Uribe
Tato Uribe

Reputation: 131

How to assign a value to a django form field in the template?

I was wondering how you can assign a value to a django form field in the template.

I know that there is other ways to assign an initial value in django, but I need to assign the value in the template because the variable is only present in the template.

The way to do this with a normal html form would be this:

{% for thing in things %}
  <p> {{ thing.content }} </p>
  <!-- Reply form -->
  <form>
    <input type="hidden" name="replyingto" value="{{ thing.number }}">
    <input type="text" label="Reply"></input>
  </form>
{% endfor %}

However, I need to use a django form.

I also know there is a way to assign a label to a field in the template, like this:

{{ form.non_field_errors }}
{{ form.field.errors }}
   <label for="{{ form.field.id_for_label }}"> field </label>
{{ form.field }}

So my question is basically how you would go about doing the example above but instead of assigning a label, assign a value.


I've found a solution!

What I did was type the html manually as Daniel suggested and assigned the value that way.

For anyone who is wondering how I did it here is an example.

Upvotes: 13

Views: 24578

Answers (2)

darkhipo
darkhipo

Reputation: 1404

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 -->
  <form FORM_PARAMS_HERE >
    <div class="form-row">
        {{ form.other_form_field.errors }}
        {{ form.other_form_field.label_tag }} {{ form.other_form_field }}
    </div>
    ... (more form rows)
    <div class="form-row">
        <input type="hidden" name="replyingto" id="replyingto_id" value="{{ thing.number }}">
        <input type="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.

Upvotes: 3

Alvin
Alvin

Reputation: 2543

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

Upvotes: 3

Related Questions