【问题标题】:How to use a checkbox in Django to enter 1 or 0 into MySQL?如何在 Django 中使用复选框在 MySQL 中输入 1 或 0?
【发布时间】:2014-09-27 10:45:24
【问题描述】:

使用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'

我想创建一个简单的表单来添加一个新的User,使用Crispy Forms,但使用默认字段,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()
        }

注意:所有classes 都用于 Twitter Bootstrap。

有没有方便的方法来做到这一点?我可以更改某处提交的数据吗?还是我应该采取不同的方法?

【问题讨论】:

标签: python mysql django django-forms django-crispy-forms


【解决方案1】:

您可以在表单中添加clean_active 方法来规范输入:

class CreateUserForm(ModelForm):
    ...

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

另请参阅:cleaning and validating form input in Django

但是,您还应该问自己,您是否真的需要以这种方式在 MySql 中表示您的数据。 方式在该字段中使用 BooleanField 而不是 IntegerField 会更方便。

【讨论】:

  • 很遗憾,如何设置数据库并不取决于我,否则我会立即更改它。
  • 这似乎没有任何效果...实际上,当我将print "hello" 放在clean_activereturn 上方时,它从未打印任何内容。不过,我正在查看您提供的更多链接。
  • 我的回答中有一个缩进错误,这会将方法置于CreateUserForm 类之外。我现在更正了。确保您没有复制错误。
【解决方案2】:

使用BooleanField 而不是IntegerField。这不需要更改数据库表,因为BooleanField 在内部将布尔值转换为 1 和 0。 MySQL 的“布尔”列类型不过是 tinyint(1) 的别名,即用作 1/0 真值的整数类型。您也可以对其他整数列类型执行此操作。

【讨论】:

  • 完美!像魅力一样工作。 :) 谢谢!
猜你喜欢
  • 2011-04-10
  • 2012-12-10
  • 1970-01-01
  • 2014-04-17
  • 2017-12-05
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多