Django:所有表单错误消息作为单个字符串

时间:2016-08-15 19:06:38

标签: django django-forms

我正在尝试在视图中以文本形式访问表单错误消息,并将其用作单个字符串。

error_string = ' '.join(form.errors['email'].as_data())

我收到此错误:

sequence item 0: expected str instance, ValidationError found

我该怎么办?

3 个答案:

答案 0 :(得分:4)

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.

答案 1 :(得分:1)

您想要将错误字符串列表加在一起,因此请使用form.errors['email']

error_string = ' '.join(form.errors['email'])

您不想使用as_data()方法,因为它返回ValidationError个实例的列表而不是字符串。

答案 2 :(得分:0)

@bdoubleu答案对我不起作用,因为它不会显示有错误的字段的名称,而只会显示错误消息

error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])

print(error_string)

>>> This field is required 

(仅显示错误,不显示字段) 如果您同时需要字段和错误消息

target = list(form.errors) + list(form.errors.values())
error_string = ' '.join([l for l in target])

print(error_string)

>>> name This field is required