如何在django表单中插入一个复选框 [英] How to insert a checkbox in a django form
本文介绍了如何在django表单中插入一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个设置页面,用户可以选择是否要接收通讯。
I've a settings page where users can select if they want to receive a newsletter or not.
我想要一个复选框,我想要Django如果newsletter在数据库中为true,请选择它。如何在Django中实现?
I want a checkbox for this, and I want that Django select it if 'newsletter' is true in database. How can I implement in Django?
推荐答案
models.py
class Settings(model.Model):
receive_newsletter = model.BooleanField()
...
forms.py
class SettingsForm(forms.ModelForm):
receive_newsletter = forms.BooleanField()
class Meta:
model = Settings
如果要根据您的应用程序中的某些条件自动将receive_newsletter设置为True,请在表单中介绍 __ init __
If you want to automatically set receive_newsletter to True according to some criteria in you application you account for that in the forms __init__
forms.py
class SettingsForm(forms.ModelForm):
receive_newsletter = forms.BooleanField()
def __init__(self):
if check_something():
self.fields['receive_newsletter'].initial = True
class Meta:
model = Settings
布尔表单字段默认使用CheckboxInput小部件。
The boolean form field uses a CheckboxInput widget by default.
这篇关于如何在django表单中插入一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文