我正在尝试在视图中以文本形式访问表单错误消息,并将其用作单个字符串。
error_string = ' '.join(form.errors['email'].as_data())
我收到此错误:
sequence item 0: expected str instance, ValidationError found
我该怎么办?
form.errors = {
'username':
['This name is reserved and cannot be registered.'],
'password2':
['This password is too short. It must contain at least 8 characters.',
'This password is too common.']
}
error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])
print(error_string)
>>> This name is reserved and cannot be registered. This password is too short. It must contain at least 8 characters. This password is too common.
您想要将错误字符串列表连接在一起,因此请使用form.errors['email']
。
error_string = ' '.join(form.errors['email'])
您不想使用as_data()
方法,因为它返回ValidationError
实例的列表而不是字符串。