mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-30 05:24:00 +03:00
Merge pull request #426 from jmagnusson/master
Support min_length / max_length kwargs on basic ModelFields
This commit is contained in:
commit
25f024575b
|
@ -215,8 +215,19 @@ class ModelField(WritableField):
|
|||
self.model_field = kwargs.pop('model_field')
|
||||
except:
|
||||
raise ValueError("ModelField requires 'model_field' kwarg")
|
||||
|
||||
self.min_length = kwargs.pop('min_length',
|
||||
getattr(self.model_field, 'min_length', None))
|
||||
self.max_length = kwargs.pop('max_length',
|
||||
getattr(self.model_field, 'max_length', None))
|
||||
|
||||
super(ModelField, self).__init__(*args, **kwargs)
|
||||
|
||||
if self.min_length is not None:
|
||||
self.validators.append(validators.MinLengthValidator(self.min_length))
|
||||
if self.max_length is not None:
|
||||
self.validators.append(validators.MaxLengthValidator(self.max_length))
|
||||
|
||||
def from_native(self, value):
|
||||
rel = getattr(self.model_field, "rel", None)
|
||||
if rel is not None:
|
||||
|
|
|
@ -35,6 +35,13 @@ def foobar():
|
|||
return 'foobar'
|
||||
|
||||
|
||||
class CustomField(models.CharField):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs['max_length'] = 12
|
||||
super(CustomField, self).__init__(*args, **kwargs)
|
||||
|
||||
|
||||
class RESTFrameworkModel(models.Model):
|
||||
"""
|
||||
Base for test models that sets app_label, so they play nicely.
|
||||
|
@ -113,6 +120,7 @@ class Comment(RESTFrameworkModel):
|
|||
class ActionItem(RESTFrameworkModel):
|
||||
title = models.CharField(max_length=200)
|
||||
done = models.BooleanField(default=False)
|
||||
info = CustomField(default='---', max_length=12)
|
||||
|
||||
|
||||
# Models for reverse relations
|
||||
|
|
|
@ -41,6 +41,7 @@ class CommentSerializer(serializers.Serializer):
|
|||
|
||||
|
||||
class ActionItemSerializer(serializers.ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = ActionItem
|
||||
|
||||
|
@ -247,6 +248,15 @@ class ValidationTests(TestCase):
|
|||
self.assertEquals(serializer.is_valid(), False)
|
||||
self.assertEquals(serializer.errors, {'title': [u'Ensure this value has at most 200 characters (it has 201).']})
|
||||
|
||||
def test_default_modelfield_max_length_exceeded(self):
|
||||
data = {
|
||||
'title': 'Testing "info" field...',
|
||||
'info': 'x' * 13,
|
||||
}
|
||||
serializer = ActionItemSerializer(data=data)
|
||||
self.assertEquals(serializer.is_valid(), False)
|
||||
self.assertEquals(serializer.errors, {'info': [u'Ensure this value has at most 12 characters (it has 13).']})
|
||||
|
||||
|
||||
class MetadataTests(TestCase):
|
||||
def test_empty(self):
|
||||
|
|
Loading…
Reference in New Issue
Block a user