Thursday, July 30, 2015

Models.clean() how to raise ValidationError WITH error_code and show field_based errors in the Form-Template?

Hi guys,

I got a working model.clean() method that actually does a great job showing the errors in the assigned html-form. The view actually marks single invalid fields red, which I find really important.

BUT:
Now I want to write a test for that model and would love to test for error_codes.

Does anyone know how to raise an error_code-exception within the model and keep the view rendering the invalid-fields correctly?

Ok... I think it's easier to understand with some code:


class MyNotebookModel(models.Model):
    note
= models.TextField()
    name
= models.CharField()

   
def clean(self):
        errors
= defaultdict(list)
       
# errors = {}  # does NOT work with view

       
# Validate self.note
       
if 'P.S. I love django!' not in self.note:
            message
= 'BadAss: Give some credits to Django!'
            errors
['note'].append(message)
           
# errors.append(ValidationError(_(message), code=1))  # does NOT work in view

       
# Validate self.name
       
if 'Steven' not in self.note:
            message
= 'BadAss: I only allow names with Steven'
            errors
['note'].append(message)
           
# errors.append(ValidationError(_(message), code=2))  # does NOT work in view

       
if len(errors):
           
raise ValidationError(errors)


class TestMyNotebookCreateView(CreateView):
   
# in my View I want to show errors by field and mark the error-fields RED
   
# it works with the above approach, but NOT with error_codes



class TestMyNotebookModelTest(unittest):
   
def test_clean(self):
       
# I'd love to be able to do a test like this one
        # and valide the error code!

        # Lets get an error-message
       
with self.assertRaises(ValidationError) as test:
            model
= MyNotebookModel()
            model
.note = 'Now this is a valid one. P.S. I love django!'
            model
.name = 'Britney is gonna fail - Hit me Baby One More Time!'
            model
.clean()
            model
.save()
       
# validate that the error messages has the right code
        the_exception
= test.exception
       
self.assertEqual(the_exception.error_code, 2)


Any ideas how to make this work?
What is best practise?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a5d1a379-5896-4743-ada9-8494f6d57284%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment