开发者

How can I update only certain fields in a Django model form?

I have a model form that I use to update a model.

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

Sometimes I don't need to update the entire model, but only want to update one of the fields. So when I POST the form only has information for the description. When I do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model.

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

Is there any way to make this ha开发者_运维问答ppen? Thanks!


Only use specified fields:

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

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

It is common to use different ModelForms for a model in different views, when you need different features. So creating another form for the model that uses the same behaviour (say clean_<fieldname> methods etc.) use:

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


If you don't want to update a field, remove it from the form via the Meta exclude tuple:

class Meta:
    exclude = ('title',)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜