类型错误无法连接' str'和' ErrorList'对象

时间:2014-03-29 14:23:26

标签: python django python-2.7

我的代码

def is_valid(self):
    form = super(UserCreateForm, self).is_valid()
    for f, error in self.errors.iteritems():
        if f != '__all_':
            self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})
    return form

回溯

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/saurabh/Desktop/project/ribbit/ribbit_app/views.py" in signup
  48.         if user_form.is_valid():

File "/home/saurabh/Desktop/project/ribbit/ribbit_app/forms.py" in is_valid
  18.                 self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})

File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in wrapper
  203.             return func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/html.py" in strip_tags
  134.         s.feed(value)

File "/usr/lib/python2.7/HTMLParser.py" in feed
  113.         self.rawdata = self.rawdata + data

Exception Type: TypeError at /signup

Exception Value: cannot concatenate 'str' and 'ErrorList' objects

1 个答案:

答案 0 :(得分:1)

Django form.errors是一个字典,键是字段名,值是lists表示错误消息的Unicode字符串。错误消息存储在lists中,因为字段可能包含多个错误消息:

>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

strip_tags(value)获取string的值,但您将list对象传递给它:

def is_valid(self):
    form = super(UserCreateForm, self).is_valid()
    for f, error in self.errors.iteritems():
        # Here `error` is a list of errors for `f` field. (may be one or more)
        if f != '__all_':
            self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})
    return form

所以你需要改变这一行:

self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})

To :(仅用于获取第一个错误)

self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error[0])})

或者:(因为有所有错误)

self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(", ".join(error))})