Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django模型形式不';设置instance=object时不填充_Python_Django_Modelform - Fatal编程技术网

Python Django模型形式不';设置instance=object时不填充

Python Django模型形式不';设置instance=object时不填充,python,django,modelform,Python,Django,Modelform,我试图用现有数据填充ModelForm(如果存在),或者创建一个新实例(如果不存在)。我已经阅读了有关堆栈溢出的文档和一些问题,但我不明白为什么我的表单没有填充现有数据。我肯定我错过了一些简单的东西,任何帮助都将不胜感激 在forms.py中: from django.forms import ModelForm, Textarea from .models import Batch class BatchForm(ModelForm): class Meta: mod

我试图用现有数据填充ModelForm(如果存在),或者创建一个新实例(如果不存在)。我已经阅读了有关堆栈溢出的文档和一些问题,但我不明白为什么我的表单没有填充现有数据。我肯定我错过了一些简单的东西,任何帮助都将不胜感激

在forms.py中:

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})}
在views.py中:(注意instance=batch参数,这应该预填充表单是否正确?)

batch_entry.html模板:

{% if batch.id > 0 %}
<h1>{{batch.date}}</h1>
<h3>{{batch.recipe}}</h3>
<form action="{% url 'logger:batch_entry' batch.id %}" method="post">
  {% csrf_token %}
  <table>
  {{BatchForm.as_table}}
  </table>
  <input type="submit" value="Submit">
</form>
{% else %}
<h1>New Batch</h1>
<form action="{% url 'logger:batch_entry' 0 %}" method="post">
  {% csrf_token %}
  <table>
  {{BatchForm.as_table}}
  </table>
  <input type="submit" value="Submit">
</form>
{% endif %}
<form action="{% url 'logger:index' %}" method="post">
  {% csrf_token %}
  <input type="submit" value="Return to Index">
</form>
{%if batch.id>0%}
{{batch.date}
{{batch.recipe}}
{%csrf_令牌%}
{{BatchForm.as_table}}
{%else%}
新批次
{%csrf_令牌%}
{{BatchForm.as_table}}
{%endif%}
{%csrf_令牌%}
因为您也在传递
请求。POST
。它应该包含提交的数据,这自然会覆盖实例中已经存在的值;但由于您是在GET上执行此操作,因此POST数据为空,因此您的表单显示为空

仅当请求实际上是POST时才将request.POST传递到表单中

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