Django

Code

Ticket #4787: ModelChoiceField_update_choices_and_fix_clean_method.patch

File ModelChoiceField_update_choices_and_fix_clean_method.patch, 2.2 kB (added by cohcheto@gmail.com, 10 months ago)

ead's patch and some modification in the clean() method

  • newforms/models.py

    old new  
    141141    # actually use any of ChoiceField's implementation. 
    142142    def __init__(self, queryset, empty_label=u"---------", cache_choices=False, 
    143143            required=True, widget=Select, label=None, initial=None, help_text=None): 
    144         self.queryset = queryset 
     144        self._queryset = queryset 
    145145        self.empty_label = empty_label 
    146146        self.cache_choices = cache_choices 
    147147        # Call Field instead of ChoiceField __init__() because we don't need 
     
    149149        Field.__init__(self, required, widget, label, initial, help_text) 
    150150        self.widget.choices = self.choices 
    151151 
     152    def _get_queryset(self): 
     153        return self._queryset 
     154 
     155    def _set_queryset(self, queryset): 
     156        self._queryset = queryset 
     157        self.widget.choices = self.choices 
     158 
     159    queryset = property(_get_queryset, _set_queryset) 
     160 
    152161    def _get_choices(self): 
    153162        # If self._choices is set, then somebody must have manually set 
    154163        # the property self.choices. In this case, just return self._choices. 
     
    160169        # *each* time _get_choices() is called (and, thus, each time 
    161170        # self.choices is accessed) so that we can ensure the QuerySet has not 
    162171        # been consumed. 
    163         return QuerySetIterator(self.queryset, self.empty_label, self.cache_choices) 
     172        return QuerySetIterator(self._queryset, self.empty_label, self.cache_choices) 
    164173 
    165174    def _set_choices(self, value): 
    166175        # This method is copied from ChoiceField._set_choices(). It's necessary 
     
    175184        if value in ('', None): 
    176185            return None 
    177186        try: 
    178             value = self.queryset.model._default_manager.get(pk=value) 
    179         except self.queryset.model.DoesNotExist: 
     187            value = self._queryset.model._default_manager.get(pk=value) 
     188            if not value in self._queryset: 
     189                raise self._queryset.model.DoesNotExist 
     190        except self._queryset.model.DoesNotExist: 
    180191            raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.')) 
    181192        return value 
    182193