24👍
ValidationError
actually holds multiple error messages.
The output of print err
is [u'Empty URL']
because that is the string returned by repr(err.messages)
(see ValidationError.__str__
source code).
If you want to print a single readable message out of a ValidationError
, you can concatenate the list of error messages, for example:
# Python 2
print '; '.join(err.messages)
# Python 3
print('; '.join(err.messages))
0👍
If you are importing ValidationError
from django.core.exceptions
you can simply use messages
method as err.messages
.
https://github.com/django/django/blob/main/django/core/exceptions.py#L124
If you are importing ValidationError
from rest_framework.serializers
, there is no messages
property for the ValidationError
but there is detail
property. so you can use err.detail
which will give you a dictionary.
In order to concatenate all the error messages as a string, you can use
"".join(["".join(v) for v in err.detail.values()])
or
"".join([k+" - "+"".join(v) for k,v in err.detail.items()])
https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py#L143
- How to display "This many months ago" in Django using Humanize?
- AuthAlreadyAssociated Exception in Django Social Auth
- Very simple user input in django
- How to manage.py loaddata in Django
- Customizing django admin ChangeForm template / adding custom content
0👍
A more general way to always know where the message is to call the dir
function on your err
variable to show you all the attribute of this object.
from that list you can infer where the messages are, in my case (with django 3.2) i found out that the message dict is in an attribute called args
.
so to use it (with a print for example)
try:
url = request.POST.get('u', '')
if len(url) == 0:
raise ValidationError('Empty URL')
except ValidationError, err:
print(err.args) # HERE THE ERROR DICT MESSAGE IS ACCESSIBLE
- How to downgrade from Django 1.7 to Django 1.6
- Logout Django Rest Framework JWT
- Validating a Django model field based on another field's value?
- One project, Multiple customers with git?
- How to override Django admin's views?
- Django – filtering by "certain value or None"
- Tiny MCE popups blank in Django admin
- Django: Password reset email subject line contains 'example.com