Modify Django Form Data Before Processing

I have a form for a model that has two fields: field_A and field_B. I want to:

  • when visualizing the form: only field_A is displayed
  • when I call form.save () field_B is saved in the model with the value from field_A

What I tried:

field_A = forms.CharField(required=True)
field_B = forms.CharField(required=False)

def save(self, *args, **kwargs):
     """
     Overriding save, so call the parent form save and return the new_user
     object.
     """
     self.data["field_B"] = self.data["field_A"]
     self.cleaned_data["username"] = self.cleaned_data["email"]
     super(MyParentClass*, self).save(*args, **kwargs) 

* both fields are inherited from ParentClass, where they are required

+5
source share
1 answer

Here is a solution that worked for me.

# models.py
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)

# forms.py
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]: 
+5

All Articles