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.
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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 Comment

For better formatting, this can be achieved with: ''.join(f'{k}: {"".join(e for e in form.errors[k])}, ' for k in form.errors)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.