[fix]validation list field with multi choice values
This commit is contained in:
parent
a8d6e59a7a
commit
e6a30f899c
@ -1080,5 +1080,9 @@ class BaseDocument(object):
|
||||
"""Return the display value for a choice field"""
|
||||
value = getattr(self, field.name)
|
||||
if field.choices and isinstance(field.choices[0], (list, tuple)):
|
||||
return dict(field.choices).get(value, value)
|
||||
sep = getattr(field, 'display_sep', u' ')
|
||||
values = value if field.__name__ == 'ListField' else [value]
|
||||
return sep.join([
|
||||
dict(field.choices).get(val, val)
|
||||
for val in values])
|
||||
return value
|
||||
|
@ -213,7 +213,9 @@ class BaseField(object):
|
||||
)
|
||||
)
|
||||
# Choices which are types other than Documents
|
||||
elif value not in choice_list:
|
||||
else:
|
||||
values = value if isinstance(value, (list, tuple)) else [value]
|
||||
if len(set(values) - set(choice_list)):
|
||||
self.error('Value must be one of %s' % six.text_type(choice_list))
|
||||
|
||||
def _validate(self, value, **kwargs):
|
||||
|
@ -920,6 +920,12 @@ class FieldTest(MongoDBTestCase):
|
||||
|
||||
def test_list_validation(self):
|
||||
"""Ensure that a list field only accepts lists with valid elements."""
|
||||
AccessLevelChoices = (
|
||||
('a', u'Administrator'),
|
||||
('b', u'Manager'),
|
||||
('c', u'Staff'),
|
||||
)
|
||||
|
||||
class User(Document):
|
||||
pass
|
||||
|
||||
@ -932,6 +938,7 @@ class FieldTest(MongoDBTestCase):
|
||||
tags = ListField(StringField())
|
||||
authors = ListField(ReferenceField(User))
|
||||
generic = ListField(GenericReferenceField())
|
||||
access_list = ListField(required=False, default=[], choices=AccessLevelChoices, display_sep=u',')
|
||||
|
||||
User.drop_collection()
|
||||
BlogPost.drop_collection()
|
||||
@ -949,6 +956,17 @@ class FieldTest(MongoDBTestCase):
|
||||
post.tags = ('fun', 'leisure')
|
||||
post.validate()
|
||||
|
||||
post.access_list = 'a,b'
|
||||
self.assertRaises(ValidationError, post.validate())
|
||||
|
||||
post.access_list = ['c', 'd']
|
||||
self.assertRaises(ValidationError, post.validate())
|
||||
|
||||
post.access_list = ['a', 'b']
|
||||
post.validate()
|
||||
|
||||
self.assertEqual(post.get_access_list_display(), u'Administrator,Manager')
|
||||
|
||||
post.comments = ['a']
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
post.comments = 'yay'
|
||||
|
Loading…
x
Reference in New Issue
Block a user