django modelform中的某些字段未更新

时间:2014-01-23 16:29:16

标签: python django django-forms

我正在使用Django模型来更新数据,由于某种原因,一个字段没有更新,而所有其他字段都没有更新。

模特:

class Five(models.Model):
    name = models.CharField(max_length=100)
    school = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    first = models.CharField(max_length=100)
    second = models.CharField(max_length=100)
    third = models.CharField(max_length=100)
    fourth = models.CharField(max_length=100)
    fifth = models.CharField(max_length=100)
    edited = models.CharField(max_length=10)
    def __unicode__(self):
        return self.name

modelForm:

class FiveForm(ModelForm):
    class Meta:
        model = Five
        exclude = ['edited']

观点:

if (request.method == "POST"):
  form = fiveForm.FiveForm(request.POST)
  edited = 1
if (form.is_valid()):
  new_five = form.save(commit=False)
  new_five.edited = edited
  new_five = form.save()

标记:

<form action="{% url 'choose' %}" method="post">
        {% csrf_token %}
        <p id="formname"></p>
        <table>
            <tr><td>Full Name:</td><td>{{ form.name }}</td></tr>
            <tr><td>Email Address:</td><td>{{ form.email }}</td></tr>
            <tr><td>Your College:</td><td>{{ form.school }}</td></tr>
            <tr><td>Choice 1:</td><td>{{ form.first }}</td></tr>
            <tr><td>Choice 2:</td><td>{{ form.second }}</td></tr>
            <tr><td>Choice 3:</td><td>{{ form.third }}</td></tr>
            <tr><td>Choice 4:</td><td>{{ form.fourth }}</td></tr>
            <tr><td>Choice 5:</td><td>{{ form.fifth }}</td></tr>
        </table>
        <input type="submit" class="btn btn-default btn-lg sub" value="High 5!" />
    </form>

出于某种原因,除了name之外的每个字段都在数据库中更新。无法理解。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

修改后,您需要调用实例new_five的save方法。

if form.is_valid():
    new_five = form.save(commit=False)
    new_five.edited = edited
    new_five.save()

目前,您正在调用表单的保存方法两次,这将无效。