【问题标题】:Python's __call__ method gets multiple values - errorPython 的 __call__ 方法获取多个值 - 错误
【发布时间】:2015-03-29 12:44:19
【问题描述】:

在 Flask 中,当我在 Jinja2 模板中呈现表单时(content = PageDownField(),后者是 TextAreaField 的子类):

{{ form.content(class_='form-control') }}

我得到错误:

__call__() got multiple values for keyword argument 'class_'

这源于以下代码行(在widget.py 中),其中class_ 已被归属。

html = super(PageDown, self).__call__(field, id = 'flask-pagedown-' + field.name, class_ = 'flask-pagedown-input', **kwargs)

快速而肮脏的解决方案是修改 Flask 扩展的PageDownclass。

有没有更优雅的方法来解决这个问题?谢谢!

【问题讨论】:

    标签: python flask jinja2 wtforms


    【解决方案1】:

    如果这个 CSS 类对你很重要,恐怕你必须编写自己的小部件,因为这个文件中还有很多其他东西是硬编码的(比如 HTML 前后字符串中的其他 CSS 类) .

    from wtforms.widgets import HTMLString, TextArea
    
    pagedown_pre_html = '''
    <div class="form-group">
    '''
    
    pagedown_post_html = '''
    </div>
    <script type="text/javascript">
    f = function() {
        if (typeof flask_pagedown_converter === "undefined")
            flask_pagedown_converter = Markdown.getSanitizingConverter().makeHtml;
        var textarea = document.getElementById("flask-pagedown-%s");
        var preview = document.createElement('div');
        preview.className = 'help-block';
        textarea.parentNode.insertBefore(preview, textarea.nextSibling);
        textarea.onkeyup = function() { preview.innerHTML = flask_pagedown_converter(textarea.value); }
        textarea.onkeyup.call(textarea);
    }
    if (document.readyState === 'complete') 
        f();
    else if (window.addEventListener)
        window.addEventListener("load", f, false);
    else if (window.attachEvent)
        window.attachEvent("onload", f);
    else
        f();
    </script>
    '''
    
    class PageDownBootstrap(TextArea):
        def __call__(self, field, **kwargs):
            html = super(PageDownBootstrap, self).__call__(field, id = 'flask-pagedown-' + field.name, class_ = 'form-control', **kwargs)
            return HTMLString(pagedown_pre_html + html + pagedown_post_html % field.name)
    

    注意在类的第 15 行替换预览块,这可能不是你想要的。根据您的需要更改它。

    另一种解决方案是使用 LESS 形式的 Bootstrap(我猜这是 form-control 的来源)并让 flask-pagedown* 类从 Bootstrap 继承正确的类。

    【讨论】:

      【解决方案2】:

      kwargs 中可能已经有一个 class_ 值。

      试试这个:

      kwargs.update(class_='flask-pagedown-input', id='flask-pagedown-' + field.name)
      html = super(PageDown, self).__call__(field, **kwargs)
      

      【讨论】:

      • OP 知道已经给出了 class_ 属性。他/她寻找一种优雅的方式来解决问题。
      猜你喜欢
      • 2019-11-29
      • 2013-07-22
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多