[英]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
:但是设计的
status
不仅仅是True
或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?) (加载
template.html
根据检索到的item.status
生成复选框的选中item.status
(选中ON
,未选中OFF
,而选中或取消选中复选框会更改相关的item.status
值?)
The only thing I've seen closest to my problem is this , but it's not the same at all.我看到的唯一与我的问题最接近的是this ,但它根本不一样。 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.首先,您的状态似乎应该是一个 BooleanField ……但是让我们假设您确实需要这些选择。
You need to tell your form to use a CheckboxInput instead of a Select.您需要告诉您的表单使用 CheckboxInput 而不是 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.
您需要将返回的布尔值转换为 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
)
Here are the part of the doc you need:以下是您需要的文档部分:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.