2014-03-29 48 views
-1

我的代碼類錯誤不能連接「海峽」和「ErrorList」對象

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 
+0

什麼這樣的背景下? – Zulu

回答

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)}) 

爲:(對於得到的只是第一個錯誤)

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))}) 
相關問題