Django Forms-如何将复选框链接到布尔字段

时间:2019-04-17 03:48:31

标签: django django-forms

python 3.6 django 1.11(尚未更新)

我想在表单中添加一个True / False复选框。我在html页面和表单本身上看到了如何执行此操作,但是两者没有链接。每当我选中True框时,代表该复选框的字段为false。

HTML

    <div class='form-group'>
    <input type="checkbox" name="donation-repeat" id="donation-repeat_id">
    <label for="donation-repeat_id">Repeat my donation (yearly)</label><br>
    </div>

Forms.py

class DonationCreateForm(forms.ModelForm):
    recurring_donation = forms.BooleanField(required = False,label = 'donation-repeat_id')
    class Meta:
        model = Donation
        fields = ['total','recurring_donation']   

    def clean_recurring_donation(self):
        print('we are cleaning now')
        print(self.cleaned_data)
        recurring_donation =  self.cleaned_data['recurring_donation']
        print('recurring_donation1 ', recurring_donation)
        return recurring_donation

Views.py

class DonationCreateView(LoginRequiredMixin, CreateView):
    form_class = DonationCreateForm
    template_name = 'donations/create.html'

    def form_valid(self, form):
        donation_form = form.save(commit=False)

但是,我总是得到这个输出 recurring_donation1 False

无论我是否选中了该框。

我在做什么错了?

3 个答案:

答案 0 :(得分:0)

我认为您应该使用NullBooleanField而不是BooleanField

class DonationCreateForm(forms.ModelForm):
    recurring_donation = forms.NullBooleanField(required=False, label='donation-repeat_id')
    # your code

答案 1 :(得分:0)

您必须将表单绑定到来自请求的数据。在您看来

 form = DonationCreationForm(request.POST)

除了提交按钮之外,还必须在模板中使用标签。

答案 2 :(得分:-1)

尝试以下操作:删除'required = False'

祝你好运!