Inverted logic in Django ModelForm

django, django-forms

Solution

Here's a custom form field that takes a boolean and flips it. The model's `public` field stays the same, but the form would use this new field to show the opposite, `private` value.

`prepare_value` flips the model's value to display the opposite on the form. `to_python` takes any incoming value from a submitted form and flips it in preparation for being saved to the model.

class OppositeBooleanField(BooleanField):
    def prepare_value(self, value):
        return not value  # toggle the value when loaded from the model

    def to_python(self, value):
        value = super(OppositeBooleanField, self).to_python(value)
        return not value  # toggle the incoming value from form submission


class MyModelForm(forms.ModelForm):
    public = OppositeBooleanField(label='Make this entry private', required=False)

    class Meta:
        model = MyModel

[Updated answer. The previous answer only handled saving a toggled form value, not displaying it properly when the value already existed.]

Problem

I've got a model in Django with a `public` boolean field that controls whether the entry is public or private. In the form, however, I should show an inverted logic: a checkbox for the `private` setting. ``` class MyModelForm(forms.ModelForm): private = forms.BooleanField(label="Make this entry private") class Meta: model = models.MyModel ``` How should I go from here?

Original source