tags:

views:

53

answers:

2

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 happen? Thanks!

A: 

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

class Meta:
    exclude = ('title',)
Daniel Roseman
This isn't exactly what I want to do. I have a single TurtleForm and at one spot on the page I want to just have the description and at another spot I want to have the full form. Is this possible or do I need to split it out into two different forms?
J. Frankenstein
+3  A: 

Only use specified fields:

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

See http://docs.djangoproject.com/en/1.2/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')
mawimawi
Thanks. The nice thing about this method is that I only need to send out the full form for populating the template and then I can choose different forms depending on what I've posted.
J. Frankenstein