5

I'm trying to access a form error message as text within a view and use it as a single string.

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

I get this error:

sequence item 0: expected str instance, ValidationError found

What should I do?

3 Answers 3

10
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.
2

You want to join a list of error strings together, so use form.errors['email'].

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

You don't want to use the as_data() method, because it returns a list of ValidationError instances instead of strings.

2

@bdoubleu answer didn't work for me, because it won't show the name of the field that has the error, only the error message,

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

print(error_string)

>>> This field is required 

(only shows the error, not the field) if you need both the field and the error message

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

print(error_string)

>>> name This field is required 
1
  • 1
    For better formatting, this can be achieved with: ''.join(f'{k}: {"".join(e for e in form.errors[k])}, ' for k in form.errors) Commented Sep 26, 2022 at 15:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.