0

我的模型中有一个布尔字段,它在视图中显示为复选框,并且我正在对其运行自定义验证。但是,我总是在模型表单的 clean 方法中将其值设为“False”,即使用户选中了该复选框,我也读到 django 自动将值转换为 False。

有人可以用我的干净方法指导我如何检查复选框是否被选中?对此问题的任何帮助将不胜感激

我的模型如下:-

discard_word =  models.BooleanField(max_length=30)

我的模型视图如下:-

if request.method == 'POST':
    form_with_post = FormSet(request.POST,queryset=page_query)
    if form_with_post.is_valid():

我的表格如下:-

class Un_Verified_bn_in_form(ModelForm):
def __init__(self, *args, **kwargs):
    super(Un_Verified_bn_in_form, self).__init__(*args, **kwargs)
    instance = getattr(self, 'instance', None)
    if instance and instance.pk:
        self.fields['phrase'].required = False
        self.fields['phrase'].widget.attrs['readonly'] = True
        self.fields['id'].widget.attrs['readonly'] = True
        self.fields['id'].required = False
        self.fields['alternate_phrase'].required = False
        #self.fields['discard_word'].required = False                                                                     
def clean(self):
    cleaned_data = self.cleaned_data
    replace_phrase = cleaned_data.get("alternate_phrase")
    discard_word_val = cleaned_data.get("discard_word")           
    if (replace_phrase == u'' or replace_phrase == None) and (discard_word_val == False ):
        raise ValidationError('You need to select atleast one field')
    return cleaned_data 

class Meta:
    model = Un_Verified_bn_in
    fields = ('id','phrase','alternate_phrase','discard_word')
    exclude = ('time','verified_by_usr','verified_by_admin','author')
4

1 回答 1

0

我不确定这是否是解决问题的正确方法,因为当复选框已签名时,浏览器会“打开”值。所以我在我的 clean 函数中使用它,我使用 self.data 而不是cleaned_data

    try:
        discard_word_val= self.data[self.prefix+'-discard_word']
    except:
        discard_word_val = False
    if discard_word_val == u'on':
        discard_word_val = True
于 2013-11-15T13:58:39.573 回答