【发布时间】: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。
有没有方便的方法来做到这一点?我可以更改某处提交的数据吗?还是我应该采取不同的方法?
【问题讨论】:
-
@JasonS 不幸的是,这并没有涵盖 MySQL 想要 1 或 0 的部分。
标签: python mysql django django-forms django-crispy-forms