django-eav2/fields.py

43 lines
1.4 KiB
Python
Raw Normal View History

2010-09-07 08:33:42 +00:00
import uuid
2010-09-07 10:11:09 +00:00
import re
2010-09-07 08:33:42 +00:00
from django.db import models
2010-09-07 12:34:03 +00:00
from django.utils.translation import ugettext_lazy as _
2010-09-07 10:11:09 +00:00
from django.core.exceptions import ValidationError
2010-09-07 13:32:53 +00:00
2010-09-07 10:11:09 +00:00
class EavSlugField(models.SlugField):
2010-09-07 11:56:35 +00:00
2010-09-07 10:11:09 +00:00
def validate(self, value, instance):
super(EavSlugField, self).validate(value, instance)
slug_regex = r'[a-z]+[a-z0-9_]*'
if not re.match(slug_regex, value):
raise ValidationError(_(u"Must be all lower case, "\
u"not start with a number, and contain "\
u"only letters, numbers, or underscores."))
2010-09-07 08:33:42 +00:00
2010-09-07 11:56:35 +00:00
@staticmethod
def create_slug_from_name(name):
'''
Creates a slug based on the name
'''
name = name.strip().lower()
2010-09-07 08:33:42 +00:00
2010-09-07 11:56:35 +00:00
# Change spaces to underscores
name = re.sub('\s+', '_', name)
2010-09-07 08:33:42 +00:00
2010-09-07 11:56:35 +00:00
# Remove non alphanumeric characters
2010-09-07 12:44:13 +00:00
return re.sub('[^\w]', '', name)
2010-09-07 13:32:53 +00:00
2010-09-07 13:40:50 +00:00
2010-09-07 13:32:53 +00:00
class EavDatatypeField(models.SlugField):
2010-09-07 13:40:50 +00:00
2010-09-07 13:32:53 +00:00
def validate(self, value, instance):
2010-09-07 13:59:45 +00:00
super(EavDatatypeField, self).validate(value, instance)
2010-09-07 13:40:50 +00:00
from .models import EavAttribute
2010-09-07 13:32:53 +00:00
if not instance.pk:
return
2010-09-07 13:40:50 +00:00
if value != EavAttribute.objects.get(pk=instance.pk).datatype:
2010-09-07 13:32:53 +00:00
raise ValidationError(_(u"You cannot change the datatype of an "
u"existing attribute."))