[英]How to set True as default value for BooleanField on Django?
I am using BooleanField
in Django.我在 Django 中使用
BooleanField
。
By default, the checkbox generated by it is unchecked state. I want the state to be checked by default.默认情况下,它生成的复选框是未选中的 state。我希望默认选中 state。 How do I do that?
我怎么做?
If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like如果您只是使用普通表单(而不是 ModelForm),您可以设置字段初始值( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field。初始) 喜欢
class MyForm(forms.Form):
my_field = forms.BooleanField(initial=True)
If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like如果您使用的是 ModelForm,则可以在模型字段 ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ) 上设置默认值,这将应用于生成的 ModelForm , 喜欢
class MyModel(models.Model):
my_field = models.BooleanField(default=True)
Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it :最后,如果你想在运行时动态选择是否将你的领域将被默认选中,您可以在使用初始参数的形式将其初始化:
form = MyForm(initial={'my_field':True})
from django.db import models
class Foo(models.Model):
any_field = models.BooleanField(default=True)
I am using django==1.11.我正在使用 django==1.11。 The answer get the most vote is actually wrong.
得票最多的答案其实是错误的。 Checking the document from django, it says:
从 django 检查文档,它说:
initial -- A value to use in this Field's initial display.
初始 - 在此字段的初始显示中使用的值。 This value is not used as a fallback if data isn't given.
如果未提供数据,则此值不用作后备。
And if you dig into the code of form validation process, you will find that, for each fields, form will call it's widget's value_from_datadict
to get actual value, so this is the place where we can inject default value.如果你深入研究表单验证过程的代码,你会发现,对于每个字段,表单都会调用它的小部件的
value_from_datadict
来获取实际值,所以这是我们可以注入默认值的地方。
To do this for BooleanField
, we can inherit from CheckboxInput
, override default value_from_datadict
and init
function.要为
BooleanField
执行此BooleanField
,我们可以从CheckboxInput
继承,覆盖默认value_from_datadict
和init
函数。
class CheckboxInput(forms.CheckboxInput):
def __init__(self, default=False, *args, **kwargs):
super(CheckboxInput, self).__init__(*args, **kwargs)
self.default = default
def value_from_datadict(self, data, files, name):
if name not in data:
return self.default
return super(CheckboxInput, self).value_from_datadict(data, files, name)
Then use this widget when creating BooleanField
.然后在创建
BooleanField
时使用这个小部件。
class ExampleForm(forms.Form):
bool_field = forms.BooleanField(widget=CheckboxInput(default=True), required=False)
from django.db import models
class Nepal(models.Model)
Is_active = models.BooleanField(default=True)
In Django 3.0 the default value of a BooleanField in model.py is set like this:在 Django 3.0 中,model.py 中BooleanField的默认值设置如下:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
I found the cleanest way of doing it is this.我发现最干净的方法是这样。
Tested on Django 3.1.5在 Django 3.1.5 上测试
class MyForm(forms.Form):
my_boolean = forms.BooleanField(required=False, initial=True)
Both initial
and default
properties were not working for me, if that's your case try this: initial
属性和default
属性都不适用于我,如果您是这种情况,请尝试以下操作:
class MyForm(forms.ModelForm):
validated = forms.BooleanField()
class Meta:
model = MyModel
fields = '__all__'
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['validated'].widget.attrs['checked'] = True
Another way to check the default state in BooleanField is:检查 BooleanField 中默认状态的另一种方法是:
active = forms.BooleanField(
widget=forms.CheckboxInput(
attrs={
'checked': True
}
)
)
I tried to change inital of BooleanField:我试图更改 BooleanField 的首字母:
def __init__(self, *args, **kwargs):
super(UserConfirmForm,self).__init__(*args, **kwargs)
self.fields['bool_field'].initial = True
but it didn't work.但它没有用。
My solve:我的解决方法:
def __init__(self, *args, **kwargs):
kwargs['initial'] = {'bool_field': True}
super(UserConfirmForm,self).__init__(*args, **kwargs)
It works like:它的工作原理如下:
UserConfirmForm(initial={'bool_field':True})
but we can't call form in Generic editing views.但我们不能在通用编辑视图中调用表单。 I think this is a great alternative to a regular call form object.
我认为这是常规呼叫表 object 的绝佳替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.