[Django]-Inverted logic in Django ModelForm

8đź‘Ť

âś…

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

👤JCotton

0đź‘Ť

You also have the option of displaying “private” in the template while keeping the django modelform field itself “public”

class MyModelForm(forms.ModelForm):
    public = forms.BooleanField(label="Make this entry private")

    class Meta:
        model = models.MyModel

HTML template:

<form>
    <p>Private: {{ form.public }}</p>
</form>

Of course, in this case, you would need to reverse the user input once the form has been submitted to correct for the toggle.

👤Suchan Lee

Leave a comment