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

问题描述 投票:0回答:2

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

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

我收到此错误:

sequence item 0: expected str instance, ValidationError found

我该怎么办?

django django-forms
2个回答
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
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.