I have a Model that looks like:
class MyModel(Model):
name = models.TextField(blank=True, default='')
bio = models.TextField(blank=True, default='')
and a ModelForm that looks like:
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('name', 'bio')
When I create/ init my form like this:
form = MyModelForm(instance=my_model, data={'bio': 'this is me'}) # where my_model has a name already set
then:
form.is_valid() # evaluates to true
form.save() # overwrites the name field in my_model and makes it blank!
Is this the expected behaviour? How would I change this so that I can ensure that if a field is not specified in the form, but it exists already in the instance that it is not overwritten with an empty string?
Note that Django only sets the
namefield to empty because you have setblank=True. If the field was required, there would be a validation error instead.Recently there was a discussion on the django-developers group about changing this behaviour. The core developers Adrian and Paul were in favour of the current behaviour.
So, if you’re going to use model forms for this view with models where you use blank=True, you’ll need to include all the model fields in your data dict. You can use the function
model_to_dictfor this.