DJango form with custom __init__ not validating

2019-08-31 12:20发布

When I use this code to customize my form's widget, it will not validate. If I comment out def __init__(..) it works fine.

class CommentForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.wysiwyg = kwargs.pop('wysiwyg', False)

        super(CommentForm, self).__init__()
        if self.wysiwyg:
            self.fields['comment_text'].widget = SummernoteWidget()
        else:
            self.fields['comment_text'].widget = forms.Textarea(attrs={'rows':2})

    comment_text = forms.CharField()

I've been able to troubleshoot this far, and the difference between the working form (no init) and the invalid form, is this:

not valid form with init:

CommentForm bound=False, valid=Unknown, fields=(comment_text)

valid form:

CommentForm bound=True, valid=Unknown, fields=(comment_text)

Is bound the problem and how do I fix it?

Thanks!

标签: django forms
1条回答
疯言疯语
2楼-- · 2019-08-31 12:52

Try this .. might work

class CommentForm(forms.Form):
def __init__(self, *args, **kwargs):
    try:
        self.wysiwyg = kwargs['wysiwyg']
    except KeyError:
        self.wysiwyg = None

    super(CommentForm, self).__init__(*args, **kwargs)
    if self.wysiwyg:
        self.fields['comment_text'].widget = SummernoteWidget()
    else:
        self.fields['comment_text'].widget = forms.Textarea(attrs={'rows':2})

comment_text = forms.CharField()
查看更多
登录 后发表回答