How do I update just one field in an instance using ModelForm if the POST request has only that one field as parameter? ModelField tries to override the fields that were not passed in the POST request with None leading to loss of data.
I have a model with +25 fields say
class C(models.Model):
a = models.CharField(max_length=128)
b = models.CharField(max_length=128)
...
x = models.IntegerField()
and I have a desktop application that does POST requests in order to edit an instance of C through an exposed api method in views.py
In the api method I am using ModelForm to validate the fields as follows:
form = CModelForm(request.POST, instance=c_instance)
if form.is_valid():
form.save()
When doing save() django either complains that some other field cannot be null or (if all fields are optional) overwrites them with None.
Does somebody know how to manage it? I would do all checks manually and update manually, but the model has so freakishly long list of fields…
You could use a subset of the fields in your ModelForm by specifying those fields as follows:
From the docs:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form