How to check if Django ValidationError subclass was raised?












0















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?










share|improve this question

























  • 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
















0















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?










share|improve this question

























  • 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














0












0








0








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?










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 17:21







y_v

















asked Nov 21 '18 at 17:14









y_vy_v

135




135













  • 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



















  • 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

















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












1 Answer
1






active

oldest

votes


















1














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 ifs is important: the second one would also be True if the first one is True.






share|improve this answer























    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    1














    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 ifs is important: the second one would also be True if the first one is True.






    share|improve this answer




























      1














      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 ifs is important: the second one would also be True if the first one is True.






      share|improve this answer


























        1












        1








        1







        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 ifs is important: the second one would also be True if the first one is True.






        share|improve this answer













        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 ifs is important: the second one would also be True if the first one is True.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 17:35









        JoseKiloJoseKilo

        1,062714




        1,062714
































            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules