How to insert a checkbox in a django form

后端 未结 4 780
猫巷女王i
猫巷女王i 2021-01-30 13:32

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

I want a checkbox for this, and I want that Django select it if \'newsletter\'

4条回答
  •  一个人的身影
    2021-01-30 13:36

    models.py:

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

    forms.py:

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

    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
    

    The boolean form field uses a CheckboxInput widget by default.

提交回复
热议问题