Django,创建多选复选框输入 [英] Django, create multiselect checkbox input

查看:131
本文介绍了Django,创建多选复选框输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有整数字段的模型,并希望在默认文本框之外使用另外一种形式的输入渲染,所以我有以下内容:

I have a model with an integer field and would like to have an alternative form input render other than the default textbox, so that I have the following:

models.py:myfield = models.IntegerField(default = 7,blank = True)

以下:


[x]选择A(值0)

[]选项B(值1)

[x]选择C(值2)

所以在保存选项将如下计算:(由于选择了A和C并且未选择2)。

So that upon save the choices would be calculated like the the following: (since choice A and C are selected and 2 is not selected).

myfield = sum(选择的选择乘以所选选项的值2)

myfield = sum(choice selected multiplied by the 2 to the value of the selected choice)

所以:


我的字段=(1 * 2 ^ 0)+(0 * 2 ^ 1)+(1 * 2 ^ 2)

我的字段= 1 + 0 + 4

我的字段= 5 #final value

my field = 5 #final value

如果这是Django之外的任何东西,那将是更直接的通过标准复选框分组,不直接映射到模型中的数据库字段,但使用Django,我目前正在亏损。

If this was anything outside of Django, it would be more straight-forward via standard Checkbox grouping that does not map directly to a database field in the model, but with Django, i'm currently at a loss.

我参考了以下资料,但仍然无法弄清楚该做什么:

I have referenced the following materials, but still am unable to figure out what to do:


小部件

modelforms

感谢您的帮助和

推荐答案

您可以使用自定义窗口小部件:

You can use custom widget like this:

from django import forms

class BinaryWidget(forms.CheckboxSelectMultiple):
    def value_from_datadict(self, data, files, name):
        value = super(BinaryWidget, self).value_from_datadict(data, files, name)
        if name == 'myfield':
            value = sum([2**(int(x)-1) for x in value])
        return value

并覆盖 myfield 在你的模型中如下:

and override myfield in your modelform as follows:

class MyModelForm(forms.ModelForm):
    ...
    myfield = forms.IntegerField(widget=BinaryWidget(choices=(
        ('1', '2^0',), ('2', '2^1',), ('3', '2^2',)
        )))

这将给你预期的结果,虽然您可能需要一个相反的功能 - 例如在编辑时设置初始值,如果是,请让我知道,所以我们可以编辑编辑。

this will give you the expected result, although you probably will need a reverse feature - set initial values when editing for example, if so please let me know, so we can figure editing as well.

这篇关于Django,创建多选复选框输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆