相关文章推荐
善良的牛肉面  ·  TLS / SSL ...·  6 月前    · 
爱热闹的金针菇  ·  java aes-128-cbc ...·  1 年前    · 
一身肌肉的烤红薯  ·  Configuration :: ...·  1 年前    · 

我想要一个复选框,如果数据库中的 "newsletter "为真,我想让Django选择它。我怎样才能在Django中实现呢?

python
django
django-forms
Fred Collins
Fred Collins
发布于 2011-06-01
4 个回答
Timmy O'Mahony
Timmy O'Mahony
发布于 2019-11-01
已采纳
0 人赞同

models.py:

class Settings(models.Model):
    receive_newsletter = models.BooleanField()
    # ...

forms.py:

class SettingsForm(forms.ModelForm):
    receive_newsletter = forms.BooleanField()
    class Meta:
        model = Settings

而如果你想根据你的应用程序中的一些标准自动将receive_newsletter设置为True,你就在表格__init__中说明。

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小部件,由违约.

Paul McMillan
Paul McMillan
发布于 2019-11-01
0 人赞同

你在你的表单上使用了一个CheckBoxInput小组件。

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxInput

如果你直接使用ModelForms,你只想在你的模型中使用一个BooleanField。

https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield

This is overall a better answer. Less code to write & using django's builtin objects for the job.
Mahadev
Mahadev
发布于 2019-11-01
0 人赞同
class PlanYourHouseForm(forms.ModelForm):
    class Meta:
        model = PlanYourHouse
        exclude = ['is_deleted'] 
        widgets = {