| 77 | # Regression test for #13184 |
| 78 | # Raising ValidationError in the custom model field |
| 79 | # with __metaclass__ = models.SubfieldBase should not cause the ValidationError |
| 80 | # to propagate beyond the methods, that perform the validation. |
| 81 | # The whole "custom type" path can be omitted, but, perhaps, |
| 82 | # it is better to include a clear example of a use case here |
| 83 | from django.core.exceptions import ValidationError |
| 85 | class CustomType(object): |
| 86 | def __init__(self, text): |
| 87 | if text != 'foo': |
| 88 | raise ValidationError('The value must be "foo", received "%s"' % text) |
| 89 | self.data = text |
| 90 | |
| 91 | class TestFieldSubfieldBase(models.Field): |
| 92 | __metaclass__ = models.SubfieldBase |
| 93 | |
| 94 | def to_python(self, value): |
| 95 | if isinstance(value, CustomType): |
| 96 | return value |
| 97 | if value is None or value == '': |
| 98 | return None |
| 99 | return CustomType(value) |
| 100 | |
| 101 | class ModelWithCustomFields(models.Model): |
| 102 | field_with_subfieldbase = TestFieldSubfieldBase() |
| 103 | |
| 104 | class Ticket13184Form(django_forms.ModelForm): |
| 105 | class Meta: |
| 106 | model = ModelWithCustomFields |
| 107 | |
| 108 | class TestTicket13184(TestCase): |
| 109 | |
| 110 | def test_valid_value_with_subfieldbase(self): |
| 111 | form = Ticket13184Form(data={u'field_with_subfieldbase':u'foo'}) |
| 112 | self.assertTrue(form.is_valid()) |
| 113 | |
| 114 | def test_invalid_value_with_subfieldbase(self): |
| 115 | form = Ticket13184Form(data={u'field_with_subfieldbase':u'bar'}) |
| 116 | self.assertFalse(form.is_valid()) |
| 117 | |
| 118 | def test_errors_with_invalid_field_value(self): |
| 119 | ''' Only the original ValidationError should appear in the errors dict ''' |
| 120 | form = Ticket13184Form(data={u'field_with_subfieldbase':u'bar'}) |
| 121 | self.assertEqual(form.errors[u'field_with_subfieldbase'], |
| 122 | [u'The value must be "foo", received "bar"']) |
| 123 | |
| 124 | def test_errors_with_empty_field_value(self): |
| 125 | '''to_python doesn't raise a ValidationError, |
| 126 | a default "required" message should be seen |
| 127 | |
| 128 | ''' |
| 129 | form = Ticket13184Form(data={u'field_with_subfieldbase':u''}) |
| 130 | self.assertEqual(form.errors[u'field_with_subfieldbase'], |
| 131 | [u'This field is required.']) |
| 132 | |
| 133 | |