繁体   English   中英

如何将复选框值链接到模型的属性?

[英]How to link checkbox value to a model's attribute?

这个想法是有这样的事情:

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)

但是设计的status不仅仅是TrueFalse

models.py

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

我将如何链接这两个值以使它们双向连接? (加载template.html根据检索到的item.status生成复选框的选中item.status (选中ON ,未选中OFF ,而选中或取消选中复选框会更改相关的item.status值?)

我看到的唯一与我的问题最接近的是this ,但它根本不一样。 我的是一个单一的二进制属性,但具有不同类型的值。

首先,您的状态似乎应该是一个 BooleanField ……但是让我们假设您确实需要这些选择。

您需要告诉您的表单使用 CheckboxInput 而不是 Select。 您需要告诉小部件哪个值应该检查小部件。 您需要将返回的布尔值转换为 Iteam.Status 属性。

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
        )

以下是您需要的文档部分:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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