多形式小部件允许我们将一些隐藏字段设置为_0 _1等,而不是。这一切都很有效,直到你的forms.MultiValueField需要开始在clean()方法中抛出ValidationError()。
Infact ... ValidationError()将表单错误设置为而不是_0或其他......
而不是在每个视图中编写一个'if'包装器来捕获并将此fieldname交换为_0 ...我是否可以在MultiWidget或MultiValueField中执行此操作?
我尝试在MultiValueField clean()函数中抛出:ValidationError({'myfieldname_0':['my error',]}),但当它被捕获到更高级别时,它只是将'my_error'保存回自我“myfieldname”哈希中的表单的__errors(不带_0)。它似乎在'site-packages / django / forms / forms.py'中以这种方式清理了。无论如何,这种方法的另一个问题是它需要硬编码我不想做的'myfieldname'。
简而言之,我想利用MultiWidget使表单简单易管理,但我希望验证在该字段的哈希响应中添加_0(在字段名称的末尾)以匹配实际输入的输入记录。这使得集成jquery.validation()(http://jqueryvalidation.org/)变得更加容易。我也愿意接受糟糕的设计......也许我只需要MutilValueField而不是MutilWidget shrugs 。
以下是设置问题的示例代码:
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,
)
答案 0 :(得分:0)
您还可以在MultiValueField的compress方法中捕获异常,这将允许您为整个字段添加异常。我维护了一个扩展MultiValueField的Feet and Inches form widget。
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
这应该允许您为所有字段或字段组合引发异常,而不是一次引发异常。希望能帮到你。
答案 1 :(得分: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%兼容(在我的问题中提到)。
希望这个答案可以帮助将来的人们!