简体   繁体   中英

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM