Here is a solution that worked for me.
class MyModel(models.Model):
field_A = models.CharField(max_length = 255)
field_B = models.CharField(max_length = 255)
def __unicode__(self):
return "%s: %s, %s" % (self.pk, self.field_A, self.field_B)
class MyModelForm(ModelForm):
class Meta:
model = MyModel
exclude = ('field_B',)
def save(self, *args, **kwargs):
commit = kwargs.pop('commit', True)
instance = super(MyModelForm, self).save(*args, commit = False, **kwargs)
instance.field_B = self.cleaned_data['field_A']
if commit:
instance.save()
return instance
Form explanation Meta
exclude = ('field_B',)
Ensures the fulfillment of the first condition. When a form is displayed to the user, it is displayed only field_A. The second condition is addressed in an overridden method save().
Explanation save()
commit = kwargs.pop('commit', True)
Retrieve the keyword argument commit, if one is specified.
instance = super(MyModelForm, self).save(*args, commit = False, **kwargs)
. commit=False, , .
instance.field_B = self.cleaned_data['field_A']
field_A cleaned_data field_B. , form.is_valid(). cleaned_data.
if commit:
instance.save()
, , .
return instance
, .
In [1]: from app.forms import MyModelForm
In [2]: f = MyModelForm(data = {'field_A': 'Value A'})
In [3]: f.is_valid()
Out[3]: True
In [4]: f.save()
Out[4]: <MyModel: 3: Value A, Value A>
In [5]: f = MyModelForm(data = {'field_A': 'VA'})
In [6]: f.is_valid()
Out[6]: True
In [7]: f.save(commit = False)
Out[7]: <MyModel: None: VA, VA>
In [8]: