【问题标题】:Django model form doesn't populate when instance=object is set设置 instance=object 时不填充 Django 模型表单
【发布时间】:2017-01-18 14:16:33
【问题描述】:

如果现有数据存在,我正在尝试用现有数据填充 ModelForm,如果不存在则创建一个新实例。我已经阅读了 django docs 和 Stack Overflow 上的几个问题,但我不明白为什么我的表单没有填充现有数据。我确定我缺少一些简单的东西,任何帮助将不胜感激。

在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 参数,这应该正确预填充表单吗?)

def batch_entry(request, batch_id):
    if int(batch_id) > 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)

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>

【问题讨论】:

    标签: python django modelform


    【解决方案1】:

    因为您传递了request.POST。这应该包含 submitted 数据,它自然会覆盖实例中已经存在的值;但由于您在 GET 上执行此操作,因此 POST 数据为空,因此您的表单显示为空。

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

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2011-12-02
      • 1970-01-01
      • 2014-06-11
      • 2015-09-02
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2014-02-14
      相关资源
      最近更新 更多