django - 如何从自定义小部件内部访问表单字段 [英] django - how can I access the form field from inside a custom widget
问题描述
以下类继承自 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}))
...
您可以看到我将 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.
看Character,你可以看到它有一个 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.
我建议您使用自定义字段来覆盖此方法并为您的自定义小部件添加一个属性.
I suggest you use a custom Field which overrides this method and adds an attribute for your custom Widget.
另外,我不确定将它留在 attrs
中是否是个好主意 - 将使用无效的
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 - 如何从自定义小部件内部访问表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!