django-eav2/fields.py

56 lines
1.9 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):
2010-09-08 18:19:51 +00:00
"""
Slugs are used to convert the Python attribute name to a database
lookup and vice versa. We need it to be a valid Python identifier.
We don't want it to start with a '_', underscore will be used
var variables we don't want to be saved in db.
"""
2010-09-07 10:11:09 +00:00
super(EavSlugField, self).validate(value, instance)
2010-09-08 18:19:51 +00:00
slug_regex = r'[a-z][a-z0-9_]*'
2010-09-07 10:11:09 +00:00
if not re.match(slug_regex, value):
raise ValidationError(_(u"Must be all lower case, "\
u"start with a letter, and contain "\
2010-09-07 10:11:09 +00:00
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
2010-09-08 18:19:51 +00:00
name = '_'.join(name.split())
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-08 19:23:42 +00:00
class EavDatatypeField(models.CharField):
2010-09-08 18:19:51 +00:00
"""
This holds checks for the attributes datatypes.
"""
2010-09-07 13:40:50 +00:00
2010-09-07 13:32:53 +00:00
def validate(self, value, instance):
2010-09-08 18:19:51 +00:00
"""
We don't want them to be able to change the attribute type
once it have been created.
"""
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."))