0

多表单小部件允许我们将一些隐藏字段设置为 _0 _1 等,而不是 . 这一切都很好,直到您的 forms.MultiValueField 需要开始在 clean() 方法中抛出 ValidationError() 。

事实上... ValidationError() 将表单错误设置为而不是 _0 或其他...

而不是在每个视图中编写一个“if”包装器来捕获并将此字段名交换为_0...有没有更简洁的方法可以在 MultiWidget 或 MultiValueField 中执行此操作?

我尝试在 MultiValueField clean() 函数中抛出:ValidationError({'myfieldname_0': ['my error',]}),但是当它在更高级别被捕获时,它只是将 'my_error' 保存回 self._errors 的'myfieldname' 哈希下的表单(没有 _0)。它似乎在“site-packages/django/forms/forms.py”中以这种方式进行了清理。无论如何,这种方法的另一个问题是它需要我对我不想做的“myfieldname”进行硬编码。

简而言之,我想利用 MultiWidget 使表单变得简单且易于管理,但我希望验证在该字段的哈希响应中添加 _0(在字段名称的末尾)以匹配实际输入记录被放入。这使得集成 jquery.validation() ( http://jqueryvalidation.org/ ) 变得更加容易。我也愿意接受糟糕的设计......也许我只需要 MutilValueField 而不是 MutilWidget耸耸肩

以下是设置我的问题的示例代码:

from django.forms import MultiWidget
from django.forms import MultiValueField
from django.forms import ModelForm
from django.forms import widgets

class MyWidget(MultiWidget):
    """

    """
    def __init__(self, attrs=None, **kwargs):

        # Populated once render() is called
        self.name = u''

        _widgets = (
            widgets.TextInput(attrs=attrs),
            widgets.HiddenInput(attrs=None),
            widgets.HiddenInput(attrs=None),
        )
        super(MyWidget, self).__init__(_widgets, attrs=None, **kwargs)

    def value_from_datadict(self, data, files, name):
        return [ widget.value_from_datadict(data, files, name + '_%s' % i)
                     for i, widget in enumerate(self.widgets)]

class MyFormField(MultiValueField):
    """
    Significantly simplified just to show my problem
    """
    widget = MyWidget

    def clean(self, value):
        # I want to some how alter how this exception is thrown so it isn't put in
        # the self._errors['<fieldname>'] hash, but instead placed in 
        # the self._errors['<fieldname>'_0] hash

        raise ValidationError(self.error_messages['required'])

class MyForm(ModelForm):
    """
   Simple form example of how I'd use the field
    """
    class Meta:
        model = <some model>

    performer = MyFormField(
        max_length=100,
        required=True,
    )
4

2 回答 2

0

您还可以在 MultiValueField 的 compress 方法中捕获异常,这将允许您为整个字段添加异常。我维护了一个扩展 MultiValueField 的英尺和英寸表单小部件

init 和 compress 部分是:

class FeetAndInchesField(MultiValueField):
    widget = FeetAndInchesWidget

    def __init__(self, *args, **kwargs):
        errors = self.default_error_messages.copy()
        if 'error_messages' in kwargs:
            errors.update(kwargs['error_messages'])
        localize = kwargs.get('localize', False)
        fields = (
            IntegerField(min_value=0, required=False, localize=localize),
            IntegerField(min_value=0, localize=localize),
            FloatField()
        )
        super(FeetAndInchesField, self).__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            feet = data_list[0]
            inches = data_list[1]
            fractional_inches = data_list[2]
            if feet == inches == fractional_inches == 0:
                raise ValidationError(u'Please specify a value for feet or inches')
            return sum_feet_inches_fractional_inches(feet, inches, fractional_inches)
        return None

这应该允许您为所有字段或字段组合引发异常,而不是一次一个。希望对您有所帮助。

于 2013-08-12T02:22:22.363 回答
0

我通过改变 MultiWidget 的默认操作解决了这个问题,如下所示:

from django.forms import MultiWidget as DjangoMultiWidget
from django.utils.safestring import mark_safe

class MultiWidget(DjangoMultiWidget):
    """
    This widget djusts the extends the existing MultiWidget to not
    place an _<index> on the first widget

    Hence a list of 3 widgets would look like:

        <input name="fieldname"/>
        <input name="fieldname_0"/>
        <input name="fieldname_1"/>

    """

    def __init__(self, *attrs, **kwargs):

        # Populated once render() is called
        self.name = u''

        super(MultiWidget, self).__init__(*attrs, **kwargs)


    def render(self, name, value, attrs=None):
        """
        We over-ride this so we can correctly extract the name

        """

        # Save Name
        self.name = name

        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id', None)

        # First Entry is not prefixed with underscore (_)
        try:
            widget_value = value[0]
        except IndexError:
            widget_value = None
        output.append(self.widgets[0].render(name, widget_value, final_attrs))

        # now we process the rest
        for i, widget in enumerate(self.widgets[1:]):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
        return mark_safe(self.format_output(output))

    def format_output(self, rendered_widgets):
        """
        Place an error class
        """
        return u''.join(rendered_widgets) + \
                u'<div class="error" for="id_%s" style="display: none;"></div>' % self.name


    def value_from_datadict(self, data, files, name):
        return [ self.widgets[0].value_from_datadict(data, files, name) ] + \
                [ widget.value_from_datadict(data, files, name + '_%s' % i)
                    for i, widget in enumerate(self.widgets[1:]) ]

这里没有魔法,因为大部分代码都是从 /django/forms/fields.py 中取出的

但是,以这种方式使用该字段允许您在没有 _0 的情况下引发标准异常,但它实际上引用了存储在以下位置的字段内容:

<input name="fieldname"/>
<input name="fieldname_0"/>
<input name="fieldname_1"/>

而不是默认的 MultiWidget 样式:

<input name="fieldname_0"/>
<input name="fieldname_1"/>
<input name="fieldname_2"/>

最终结果是 Django 的框架,并且错误处理与 JQuery 的验证插件(在我的问题中提到)变得 100% 兼容。

希望这个答案对未来的人们有所帮助!

于 2013-08-16T01:50:17.350 回答