mashedpotatoes
mashedpotatoes

Reputation: 435

How to link checkbox value to a model's attribute?

The idea is to have something like this:

template.html

{% for item in items %}
    <input type="checkbox" checked= {{ item.status }}>
{% endfor %}

views.py

def index(request):
    context = { 'items' : Item.objects.all() }
    return render(request, 'template.html', context)

But the status by design isn't simply True or False:

models.py

class Item(models.Model):
    class Status(models.TextChoices):
        ON = 1
        OFF = 0
    status = models.IntegerField(choices=Status.choices)
    # other attributes.. 

How will I link these two values so that they're two-way connected? (Loading template.html yields the checkbox's checked-ness based on the retrieved item.status (checked for ON, unchecked for OFF, while checking or unchecking the checkboxes will change the related item.status value?)

The only thing I've seen closest to my problem is this, but it's not the same at all. Mine is a single binary attribute but has different kinds of values.

Upvotes: 0

Views: 391

Answers (1)

Nicolas Appriou
Nicolas Appriou

Reputation: 2331

First of all, it seems that your status should be a BooleanField... But let's assume you really need those choices.

You need to tell your form to use a CheckboxInput instead of a Select. You need to tell the widget which value should check the widget. You need to convert the returned boolean as an Iteam.Status attribute.

class Form(forms.ModelForm):
    class Meta:
        model = Item
        fields = ('status',)
        widgets = {
            'status': forms.CheckboxInput(
                check_test=lambda status: status == Item.Status.ON,
            ),
        }

    def clean_status(self):
        return (
            Item.Status.ON if self.cleaned_data.get('status')
            else Item.Status.OFF
        )

Here are the part of the doc you need:

Upvotes: 2

Related Questions