From ae48939c33373d4ffca4851271bed7887e34b344 Mon Sep 17 00:00:00 2001 From: Damien Nozay Date: Sun, 4 Jan 2015 12:58:58 -0800 Subject: [PATCH] Allow ChoiceField to specify defaults directly on class --- rest_framework/fields.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index df021d724..1fc36e155 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1005,8 +1005,18 @@ class ChoiceField(Field): default_error_messages = { 'invalid_choice': _('`{input}` is not a valid choice.') } + # allows subclasses to change defaults + allow_blank = False + choices = None + + def __init__(self, *args, **kwargs): + if args: + choices = args[0] + else: + choices = kwargs.pop('choices', self.choices) + # not available on class or as kwarg + assert choices is not None, 'need to specify `choices`.' - def __init__(self, choices, **kwargs): # Allow either single or paired choices style: # choices = [1, 2, 3] # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] @@ -1026,7 +1036,7 @@ class ChoiceField(Field): (six.text_type(key), key) for key in self.choices.keys() ]) - self.allow_blank = kwargs.pop('allow_blank', False) + self.allow_blank = kwargs.pop('allow_blank', self.allow_blank) super(ChoiceField, self).__init__(**kwargs)