Django model form doesn't populate when instance=object is set
<p>I'm trying to populate a ModelForm with existing data if it exists or create a new instance if not. I've read the <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/" rel="nofollow">django docs</a> and several questions here on Stack Overflow but I can't figure out why my form doesn't populate with the existing data. I'm sure I'm missing something simple, any help would be appreciated.</p>

<p>In forms.py:</p>

<pre><code>from django.forms import ModelForm, Textarea
from .models import Batch

class BatchForm(ModelForm):
    class Meta:
        model = Batch
        fields = ('recipe', 'date', 'original_gravity', 'final_gravity', 'gravity_units', 'notes')
        widgets = {'notes': Textarea(attrs={'cols': 40, 'rows': 10})}
</code></pre>

<p>in views.py: (notice the instance=batch argument, this should pre-populate the form correct?)</p>

<pre><code>def batch_entry(request, batch_id):
    if int(batch_id) &gt; 0:
        batch = get_object_or_404(Batch, id=batch_id)
        form = BatchForm(request.POST, instance=batch)
        context = {'BatchForm': form, 'batch': batch }
    else:
        form = BatchForm()
        context = {'BatchForm': form, 'batch': None }
    return render(request, 'logger/batch_entry.html', context)
</code></pre>

<p>the batch_entry.html template:</p>

<pre><code>{% if batch.id &gt; 0 %}
&lt;h1&gt;{{batch.date}}&lt;/h1&gt;
&lt;h3&gt;{{batch.recipe}}&lt;/h3&gt;
&lt;form action="{% url 'logger:batch_entry' batch.id %}" method="post"&gt;
  {% csrf_token %}
  &lt;table&gt;
  {{BatchForm.as_table}}
  &lt;/table&gt;
  &lt;input type="submit" value="Submit"&gt;
&lt;/form&gt;
{% else %}
&lt;h1&gt;New Batch&lt;/h1&gt;
&lt;form action="{% url 'logger:batch_entry' 0 %}" method="post"&gt;
  {% csrf_token %}
  &lt;table&gt;
  {{BatchForm.as_table}}
  &lt;/table&gt;
  &lt;input type="submit" value="Submit"&gt;
&lt;/form&gt;
{% endif %}
&lt;form action="{% url 'logger:index' %}" method="post"&gt;
  {% csrf_token %}
  &lt;input type="submit" value="Return to Index"&gt;
&lt;/form&gt;
</code></pre>

<p>Because you're <em>also</em> passing <code>request.POST</code>. That is supposed to contain the <em>submitted</em> data, which would naturally override the values already in the instance; but since you're doing that on a GET, the POST data is empty, so your form is displayed empty.</p>

<p>Only pass request.POST into the form when the request is actually a POST.</p>

python django modelform