3 ms·
less magic: from django.db import models +from django.core.exceptions import ValidationError +def not_empty(value): + if value == u''
by cma 14y ago
less magic:
from django.db import models
+from django.core.exceptions import ValidationError
+def not_empty(value):
+ if value == u'': raise ValidationError(u'Empty value')
class MyModel(models.Model):
- name = models.CharField(max_length=50, blank=True)
+ name = models.CharField(max_length=50, blank=True, validators=[not_empty])
- pydanny 14y agoNice!
- obviouslygreen 14y agoReference: https://docs.djangoproject.com/en/dev/ref/validators/ https://docs.djangoproject.com/en/dev/ref/validators/
- whubr 14y agoBlank is purely for validation and has nothing to do with the database constraints. If you want to prevent empty input just remove 'blank=True', surely? https://docs.djangoproject.com/en/dev/ref/models/fields/#blank https://docs.djangoproject.com/en/dev/ref/models/fields/#bla...
- cma 14y agoYep, I assumed that wasn't the case based on the blog post's goal of avoiding changing the schema (I thought blank=True must be adding a CHECK (column_name <> '') constraint or something).
- eurleif 14y ago'if not value.strip():' is a more thorough check that I think is better in most cases.