How to check if Django ValidationError subclass was raised?
Let's assume I have a Django model:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
I would like to create model instance and validate it:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
But the code above will never print "Hello!"
because full_clean
method is raising only ValidationError
.
Can anyone suggest, how to call full_clean
and check if ValidationError
subclass exception was raised?
python django python-2.7 django-1.6
add a comment |
Let's assume I have a Django model:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
I would like to create model instance and validate it:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
But the code above will never print "Hello!"
because full_clean
method is raising only ValidationError
.
Can anyone suggest, how to call full_clean
and check if ValidationError
subclass exception was raised?
python django python-2.7 django-1.6
A simpleexcept ValidationError
will handle all instances of subclasses as well.
– schwobaseggl
Nov 21 '18 at 17:18
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
The underlying exceptions are collected in thefull_clean
and still accessible. See the answer.
– schwobaseggl
Nov 21 '18 at 17:39
add a comment |
Let's assume I have a Django model:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
I would like to create model instance and validate it:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
But the code above will never print "Hello!"
because full_clean
method is raising only ValidationError
.
Can anyone suggest, how to call full_clean
and check if ValidationError
subclass exception was raised?
python django python-2.7 django-1.6
Let's assume I have a Django model:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
I would like to create model instance and validate it:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
But the code above will never print "Hello!"
because full_clean
method is raising only ValidationError
.
Can anyone suggest, how to call full_clean
and check if ValidationError
subclass exception was raised?
python django python-2.7 django-1.6
python django python-2.7 django-1.6
edited Nov 21 '18 at 17:21
y_v
asked Nov 21 '18 at 17:14
y_vy_v
135
135
A simpleexcept ValidationError
will handle all instances of subclasses as well.
– schwobaseggl
Nov 21 '18 at 17:18
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
The underlying exceptions are collected in thefull_clean
and still accessible. See the answer.
– schwobaseggl
Nov 21 '18 at 17:39
add a comment |
A simpleexcept ValidationError
will handle all instances of subclasses as well.
– schwobaseggl
Nov 21 '18 at 17:18
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
The underlying exceptions are collected in thefull_clean
and still accessible. See the answer.
– schwobaseggl
Nov 21 '18 at 17:39
A simple
except ValidationError
will handle all instances of subclasses as well.– schwobaseggl
Nov 21 '18 at 17:18
A simple
except ValidationError
will handle all instances of subclasses as well.– schwobaseggl
Nov 21 '18 at 17:18
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
The underlying exceptions are collected in the
full_clean
and still accessible. See the answer.– schwobaseggl
Nov 21 '18 at 17:39
The underlying exceptions are collected in the
full_clean
and still accessible. See the answer.– schwobaseggl
Nov 21 '18 at 17:39
add a comment |
1 Answer
1
active
oldest
votes
The full_clean
method collects all the errors raised on several phases.
You can check how it's calling your clean
method here: https://github.com/django/django/blob/master/django/db/models/base.py#L1150
Luckily, the original exceptions are preserved inside error_dict
.
You can try this:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
Assuming that CustomValidationError
is only raised from the clean
method. Otherwise you would also need to check other keys in error_dict
.
Note that the order of the if
s is important: the second one would also be True if the first one is True.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417382%2fhow-to-check-if-django-validationerror-subclass-was-raised%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The full_clean
method collects all the errors raised on several phases.
You can check how it's calling your clean
method here: https://github.com/django/django/blob/master/django/db/models/base.py#L1150
Luckily, the original exceptions are preserved inside error_dict
.
You can try this:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
Assuming that CustomValidationError
is only raised from the clean
method. Otherwise you would also need to check other keys in error_dict
.
Note that the order of the if
s is important: the second one would also be True if the first one is True.
add a comment |
The full_clean
method collects all the errors raised on several phases.
You can check how it's calling your clean
method here: https://github.com/django/django/blob/master/django/db/models/base.py#L1150
Luckily, the original exceptions are preserved inside error_dict
.
You can try this:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
Assuming that CustomValidationError
is only raised from the clean
method. Otherwise you would also need to check other keys in error_dict
.
Note that the order of the if
s is important: the second one would also be True if the first one is True.
add a comment |
The full_clean
method collects all the errors raised on several phases.
You can check how it's calling your clean
method here: https://github.com/django/django/blob/master/django/db/models/base.py#L1150
Luckily, the original exceptions are preserved inside error_dict
.
You can try this:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
Assuming that CustomValidationError
is only raised from the clean
method. Otherwise you would also need to check other keys in error_dict
.
Note that the order of the if
s is important: the second one would also be True if the first one is True.
The full_clean
method collects all the errors raised on several phases.
You can check how it's calling your clean
method here: https://github.com/django/django/blob/master/django/db/models/base.py#L1150
Luckily, the original exceptions are preserved inside error_dict
.
You can try this:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except ValidationError as exc:
for original_exc in exc.error_dict['__all__']:
if isinstance(original_exc, MyDjangoModel.CustomValidationError):
print("Hello!")
elif isinstance(original_exc, ValidationError):
print("Bye!")
Assuming that CustomValidationError
is only raised from the clean
method. Otherwise you would also need to check other keys in error_dict
.
Note that the order of the if
s is important: the second one would also be True if the first one is True.
answered Nov 21 '18 at 17:35
JoseKiloJoseKilo
1,062714
1,062714
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417382%2fhow-to-check-if-django-validationerror-subclass-was-raised%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
A simple
except ValidationError
will handle all instances of subclasses as well.– schwobaseggl
Nov 21 '18 at 17:18
@schwobaseggl yes, thank You, but I would like to add custom logic when subclass of ValidationError is raised.
– y_v
Nov 21 '18 at 17:22
The underlying exceptions are collected in the
full_clean
and still accessible. See the answer.– schwobaseggl
Nov 21 '18 at 17:39