【问题标题】:Overwrite clean method in Django Custom Forms在 Django 自定义表单中覆盖 clean 方法
【发布时间】:2010-03-03 14:03:47
【问题描述】:

我写了一个自定义小部件

class AutoCompleteWidget(widgets.TextInput):
"""
widget to show an autocomplete box which returns a list on nodes available to be tagged
"""
def render(self, name, value, attrs=None):
    final_attrs = self.build_attrs(attrs, name=name)

    if not self.attrs.has_key('id'):
        final_attrs['id'] = 'id_%s' % name

    if not value: value = '[]'

    jquery = u"""
    <script type="text/javascript">
    $("#%s").tokenInput('%s', {
        hintText: "Enter the word",
        noResultsText: "No results",
        prePopulate: %s,
        searchingText: "Searching..."
    });

    $("body").focus();
    </script>
    """ % (final_attrs['id'], reverse('ajax_autocomplete'), value)

    output = super(AutoTagWidget, self).render(name, "", attrs)

    return output + mark_safe(jquery)

class MyForm(forms.Form):
    AutoComplete = forms.CharField(widget=AutoCompleteWidget)

此小部件使用jquery function,它根据数据库中的条目自动完成单词。您可以通过将 prePopulate 设置为格式为

的 json 字符串来预设其初始值
['name': 'some name', 'id': 'some id']

我通过将表单字段的初始值设置为此 json 字符串来做到这一点

jquery_string = ['name': 'some name', 'id': 'some id']
form = MyForm(initial={'AutoComplete':jquery_string})

提交表单时,AutoComplete 的值以逗号分隔列表的形式返回,其中包含所选 ID,例如12,45,43,66,如果我想要的话。

但是,如果表单中有错误,例如未输入必填字段,则自动完成字段的值现在是 12、45、43、66,而不是它需要的 json 字符串。

解决此问题的最佳方法是什么。我正在考虑覆盖表单类中的 clean 方法,但我不确定如何找出是否有任何其他元素返回了错误。例如

if forms.errors
   form.cleaned_date['autocomplete'] = json string

return form.cleaned_data

谢谢

【问题讨论】:

    标签: django django-forms django-widget


    【解决方案1】:

    那么为什么不能在适当的字段清理方法中进行清理呢?

    我还使用相同的技术使用自定义小部件生成自动完成字段。 当用户从小部件中选择一些结果时,我的 js 代码用正确的 id 填充隐藏的“id”字段,然后我有这个字段清理方法:

     def clean_category(self):
            try:
                category = Category.objects.get(id=int(self.cleaned_data['category']))
            except:
                raise forms.ValidationError("Such category doesn't exist")
            return category
    

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2017-05-03
      • 2011-01-08
      • 1970-01-01
      相关资源
      最近更新 更多