如何仅更新Django模型表单中的某些字段?

时间:2010-06-15 17:57:00

标签: python django

我有一个用于更新模型的模型表单。

class Turtle(models.Model):
    name = models.CharField(max_length=50, blank=False)
    description = models.TextField(blank=True)

class TurtleForm(forms.ModelForm):
    class Meta:
        model = Turtle

有时我不需要更新整个模型,只想更新其中一个字段。因此,当我发布表格时,只有描述信息。当我这样做时,模型永远不会保存,因为它认为名称被删除,而我的意图是名称没有改变,只是从模型中使用。

    turtle_form = TurtleForm(request.POST, instance=object)
    if turtle_form.is_valid():
        turtle_form.save()

有没有办法让这种情况发生?谢谢!

2 个答案:

答案 0 :(得分:9)

仅使用指定的字段:

class FirstModelForm(forms.ModelForm):
    class Meta:
        model = TheModel
        fields = ('title',)
    def clean_title(self....

请参阅http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude

当您需要不同的功能时,通常在不同视图中对模型使用不同的ModelForms。因此,为使用相同行为的模型创建另一个表单(比如clean_<fieldname>方法等),使用:

class SecondModelForm(FirstModelForm):
    class Meta:
        model = TheModel
        fields = ('title', 'description')

答案 1 :(得分:1)

如果您不想更新字段,请通过元exclude元组将其从表单中删除:

class Meta:
    exclude = ('title',)