In Django forms.ModelChoiceField HOWTO restrict displayed choices but set one of the restricted values during cleanup
I have a custom field which subclasses ModelMultipleChoiceField. I provide the choices to be displayed via queryset parameter. This queryset excludes certain values. My problem comes when during cleanup operation for some workflows I need to select an option which was initially excluded by the way of queryset. When I try to save this value django refuses to save it saying that it is not a valid option. On looking up the clean method for ModelMultipleChoic开发者_JS百科eField I found that it checks if the provided "value" is from within the initial queryset, which causes my dilemma.
I wanted to know if it is possible to circumvent this problem without any major hacks.
django/forms/models.py:1011 has this:
qs = self.queryset.filter(**{'%s__in' % key: value})
So it seems that if you overrode your custom field's clean() method to modify self.queryset as necessary before calling super(MyField, self).clean(value)
, you could handle this edge case relatively cleanly.
精彩评论