[Answer]-How to control which fields from POST data in ModelForm overwrite fields from instance that is passed in?

1πŸ‘

βœ…

If param1 and param2 depend on each other then you need to write a .clean() function on your form:

from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param1','param2')

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        param1 = cleaned_data.get("param1")
        param1 = cleaned_data.get("param2")

        if param1 and param2:
            # Only do something if both fields are valid so far.
            if param1 != param2:
                raise forms.ValidationError("param1 does not equal param2")

        return cleaned_data

If param1 and param2 ~do not~ depend on each other then you need to write a .clean_<fieldname>() function on your form:

from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('param1','param2')

    def clean_param1(self):
        data = self.cleaned_data['param1']

        if data == 'spam':
            raise forms.ValidationError("param1 is spam")

        return data
πŸ‘€Scott Woodall

0πŸ‘

This form will dynamically exclude any fields submitted with empty values, so they won’t overwrite anything on the existing model instance:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, data=None, *args, **kwargs):
        if data is not None:
            for key, value in data.items():
                if value.strip() == '':
                    exclude = set(self._meta.exclude or [])
                    exclude.add(key)
                    self._meta.exclude = tuple(exclude)
        super(MyForm, self).__init__(data=data, *args, **kwargs)
πŸ‘€Anentropic

Leave a comment