Skip to content

Commit

Permalink
[1730][validators, converters] Update convert_to_tags
Browse files Browse the repository at this point in the history
to take input from a html select instead of a tag string.

Add additional validator to check that a tag belongs
to a given vocab.
  • Loading branch information
johnglover committed Feb 8, 2012
1 parent 335535b commit 2044924
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
19 changes: 12 additions & 7 deletions ckan/logic/converters.py
@@ -1,9 +1,9 @@
from pylons.i18n import _
from ckan import model
from ckan.model import vocabulary
from ckan.lib.navl.dictization_functions import Invalid
from ckan.lib.field_types import DateType, DateConvertError
from ckan.logic.validators import tag_length_validator, tag_name_validator
from ckan.logic.validators import tag_length_validator, tag_name_validator, \
tag_in_vocabulary_validator

def convert_to_extras(key, data, errors, context):
extras = data.get(('extras',), [])
Expand Down Expand Up @@ -44,22 +44,27 @@ def free_tags_only(key, data, errors, context):

def convert_to_tags(vocab):
def callable(key, data, errors, context):
tag_string = data.get(key)
new_tags = [tag.strip() for tag in tag_string.split(',') if tag.strip()]
new_tags = data.get(key)
if not new_tags:
return
if isinstance(new_tags, basestring):
new_tags = [new_tags]

# get current number of tags
n = 0
for k in data.keys():
if k[0] == 'tags':
n = max(n, k[1] + 1)

for tag in new_tags:
tag_length_validator(tag, context)
tag_name_validator(tag, context)
v = model.Vocabulary.get(vocab)
if not v:
raise Invalid(_('Tag vocabulary "%s" does not exist') % vocab)
context['vocabulary'] = v

for tag in new_tags:
tag_length_validator(tag, context)
tag_name_validator(tag, context)
tag_in_vocabulary_validator(tag, context)

for num, tag in enumerate(new_tags):
data[('tags', num+n, 'name')] = tag
Expand Down
16 changes: 15 additions & 1 deletion ckan/logic/validators.py
@@ -1,6 +1,6 @@
import re
import datetime
from pylons.i18n import _, ungettext, N_, gettext
from pylons.i18n import _
from ckan.lib.navl.dictization_functions import Invalid, Missing, missing, unflatten
from ckan.authz import Authorizer
from ckan.logic import check_access, NotAuthorized
Expand Down Expand Up @@ -348,3 +348,17 @@ def vocabulary_id_exists(value, context):
if not result:
raise Invalid(_('Tag vocabulary was not found.'))
return value

def tag_in_vocabulary_validator(value, context):
model = context['model']
session = context['session']
vocabulary = context.get('vocabulary')
if vocabulary:
query = session.query(model.Tag)\
.filter(model.Tag.vocabulary_id==vocabulary.id)\
.filter(model.Tag.name==value)\
.count()
if not query:
raise Invalid(_('Tag %s does not belong to vocabulary %s') % (value, vocabulary.name))
return value

0 comments on commit 2044924

Please sign in to comment.