Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverted logic in Django ModelForm

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?

like image 877
Luís Guilherme Avatar asked Jan 01 '26 09:01

Luís Guilherme


1 Answers

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.]

like image 61
JCotton Avatar answered Jan 04 '26 00:01

JCotton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!