如何在 Django 表单中插入复选框 [英] How to insert a checkbox in a django form

查看:24
本文介绍了如何在 Django 表单中插入复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置页面,用户可以在其中选择是否要接收时事通讯.

I've a settings page where users can select if they want to receive a newsletter or not.

我想要一个复选框,如果数据库中的newsletter"为真,我希望 Django 选择它.如何在 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(models.Model):
    receive_newsletter = models.BooleanField()
    # ...

forms.py:

class SettingsForm(forms.ModelForm):
    receive_newsletter = forms.BooleanField()

    class Meta:
        model = Settings

如果您想根据应用程序中的某些条件自动将 receive_newsletter 设置为 True,请在 __init__ 表单中说明:

And if you want to automatically set receive_newsletter to True according to some criteria in your application, you account for that in the forms __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小部件.

The boolean form field uses a CheckboxInput widget by default.

这篇关于如何在 Django 表单中插入复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆