On 01/06/12 14:47, David Markey wrote:
Hi All,

Say I have this model

class TestModel(models.Model):
    my_test = models.CharField(max_length=512, blank=True)

And I try this:

In [1]: from core.base.models import TestModel

In [2]: test_model = TestModel()

In [3]: test_model.my_test =*""*

In [4]: test_model.full_clean()

In [5]: test_model.save()

*Ok cool, this is expected.*
*
*
*How about:*


In [6]: test_model2 = TestModel()

In [7]: test_model2.my_test =*None*

In [8]: test_model2.full_clean()

In [9]: test_model2.save()

##*IntegrityError raised*

Is there a way for full_clean() to catch that the "my_test" field is Null when it shouldn't be, when blank=True?

If I have blank=False, it wont validate when my_test="".



I think the behaviour is explained by the clean_fields method called by full_clean:

        for f in self._meta.fields:
            if f.name in exclude:
                continue
* # Skip validation for empty fields with blank=True. The developer
            # is responsible for making sure they have a valid value.
*            raw_value = getattr(self, f.attname)
            if f.blank and raw_value in validators.EMPTY_VALUES:
                continue

https://github.com/django/django/blob/master/django/db/models/base.py#L851

I can't think of a way for you to avoid checking for whether test_model2.my_test is None. Can you change the code that is assigning test_model2.my_test = None? The default value for the CharField is the empty string, which as you show in your first example, doesn't cause a problem.

Cheers,
Alasdair

--
Alasdair Nicol
Developer, MEMSET

mail: [email protected]
 web: http://www.memset.com/

Memset Ltd., registration number 4504980. 25 Frederick Sanger Road, Guildford, 
Surrey, GU2 7YD, UK.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to