如何从自定义窗口小部件内部访问表单域

如何从自定义窗口小部件内部访问表单域

本文介绍了django - 如何从自定义窗口小部件内部访问表单域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

下面的类继承自 Textarea 小部件,并具有javascript代码,显示用户可以在文本区域中输入多少个字符。

The below class inherits from the Textarea widget and features javascript code that displays how many characters more a user can enter in a textarea.

class TextAreaWithCharCounter(forms.Textarea):

    class Media:
        js = ('js/jquery.charcounter.js',)

    def render(self, name, value, attrs = None):
        id = attrs['id']
        max_length = self.attrs.get('max_length', 200)
        output = super(TextAreaWithCharCounter, self).render(name, value, attrs)
        output += mark_safe(u'''
                        <script type="text/javascript">
                        $("#%s").charCounter(%d, {classname:"charcounter"});
                        </script>'''%(id, max_length))
        return output

表单的相关部分代码如下:

The relevant portion of the form code is as follows:

class MyForm(forms.Form):
    foo = forms.CharField(max_length = 200, widget = TextAreaWithCharCounter(attrs={'max_length':200}))
    ...

ÿ ou可以看到我传递了 max_length 参数两次,一个用于该字段,一个用于小部件。更好的方法可能是从窗口小部件内部访问窗体字段,并获取其max_length属性,以便窗口小部件不需要max_length参数。如何做到这一点?

You can see that I pass the max_length argument twice, one for the field and one for the widget. A better way may be accessing the form field from inside the widget and get its max_length attribute, so that a max_length argument won't be required by the widget. How can I do that?

推荐答案

从技术上讲,Widget不一定要直接关系到Field你不这样做。

Technically, a Widget doesn't have to have a direct relationship back to a Field, so you don't do this.

查看,你可以看到它有一个 widget_attrs 方法自动将 maxlength 属性添加到 TextInput / PasswordInput 字段。

Looking at the source of CharField, you can see that it has a widget_attrs method which automatically adds the maxlength attribute to TextInput / PasswordInput fields.

我建议您使用自定义字段来覆盖此方法,并为自定义Widget添加一个属性。

I suggest you use a custom Field which overrides this method and adds an attribute for your custom Widget.

此外,我不确定将它留在 attrs 是一个好主意,无论如何 - < TextArea> 将以无效的 max_length 参数呈现。也许你应该是 pop()取而代之?

Also, I'm not sure that leaving it in attrs is a good idea anyway - the <TextArea> will be rendered with an invalid max_length argument. Perhaps you should be pop()ing it off instead?

这篇关于django - 如何从自定义窗口小部件内部访问表单域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:34