[Django]-Does Django ModelForm set unspecified fields to empty?

10👍

Note that Django only sets the name field to empty because you have set blank=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_dict for this.

from django.forms.models import model_to_dict
data = model_to_dict(my_model)
data.update({'bio': 'this is me'}) # or data.update(request.POST) 
form = MyModelForm(instance=my_model, data=data)

2👍

Providing the instance argument to a ModelForm is the same as passing initial, i.e. they serve the same purpose. What gets save is always the data. If a field in that dict is empty, then it will be when the model is saved as well.

If you want to maintain the entire state of the model when only dealing with a single field as data. Then, try something like the following:

data = my_model.__dict__
data['bio'] = request.POST.get('bio')
MyModelForm(instance=my_model, data=data)

0👍

If you want to pass initial data to the form, use initial instead of data

MyModelForm(instance=my_model, initial={'bio': 'this is me'})
                               ^

[edit]

If you have included the field for name in your form

fields = ('name', 'bio')

but do not pass any data for “name”

data={'bio': 'this is me'}

The form field will behave as if the name had been submitted blank.

Which is allowed in your model, so is_valid() will be True

name = models.TextField(blank=True, default='')
👤alex

Leave a comment