如何在Django中使用复选框将1或0输入MySQL?

0 投票
2 回答
1624 浏览
提问于 2025-04-18 15:59

我用 inspectdb 工具生成了一个 User 表的模型,内容如下:

class User(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(unique=True, max_length=128)
    active = models.IntegerField(blank=True, null=True)
    created_date = models.DateTimeField()
    class Meta:
        managed = False
        db_table = 'user'

我想用 Crispy Forms 创建一个简单的表单来添加新的 User。但是在默认字段中,active 这个字段变成了数字输入框,而我更希望它是一个复选框。不过,单纯把这个字段设置为 CheckboxInput 并不能解决问题,因为它不会自动把开关状态转换为 1/0。以下是我的表单,供你参考:

class CreateUserForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3 col-md-2 col-sm-2'
        self.helper.field_class = 'col-lg-6 col-md-8 col-sm-10'
        self.helper.layout = Layout(
            'name',
            'active',
            FormActions(
                Submit('submit', 'Submit'),
                HTML('<a class="btn btn-default" href="{% url "app:user:list" page="1" %}">Cancel</a>'),
            ),
        )

    class Meta:
        model = User
        fields = ['name', 'active']
        widgets = {
            'note': Textarea(attrs={'cols': 23, 'rows': 4}),
            'active': CheckboxInput()
        }

注意:所有的 class 是为了配合 Twitter Bootstrap 使用的。

有没有什么简单的方法可以做到这一点?我可以在某个地方修改提交的数据吗?还是说我应该换个方法?

2 个回答

0

你可以在你的表单里添加一个 clean_active 方法来规范输入的数据:

class CreateUserForm(ModelForm):
    ...

    def clean_active(self):
        return 1 if self.cleaned_data['active'] else 0

另外,你可以查看这个链接:在Django中清理和验证表单输入

不过,你也要问问自己,真的有必要把数据以那种方式存储在MySql里吗?其实用 BooleanField(布尔字段)来代替 IntegerField(整数字段)会方便得多。

4

BooleanField代替IntegerField。这样做不需要更改数据库表,因为BooleanField内部会把布尔值转换成1和0。其实,MySQL里的“boolean”列类型也只是tinyint(1)的别名,也就是用整数类型表示真(1)和假(0)的值。你也可以用其他整数列类型来做到这一点。

撰写回答