from django.newforms.models import QuerySetIterator
from django import newforms as forms
class CustomQuerySetIterator(QuerySetIterator):
def __iter__(self):
if self.empty_label is not None:
yield (u"", self.empty_label)
for obj in self.queryset:
yield (obj.pk, obj.__dict__[self.label_field])
if not self.cache_choices:
self.queryset._result_cache = None
def __init__(self,*args,**kwargs):
self.label_field = kwargs['label_field']
super(CustomQuerySetIterator,self).__init__(*args)
class CustomChoiceField(forms.ModelChoiceField):
def _get_choices(self):
if hasattr(self, "_choices"):
return self._choices
return CustomQuerySetIterator(self.queryset, self.empty_label,self.cache_choices,label_field=self.label_field)
choices = property(_get_choices, forms.ModelChoiceField._set_choices)
def __init__(self, *args, **kwargs):
self.label_field = kwargs['label_field']
del kwargs['label_field']
super(CustomChoiceField,self).__init__(*args, **kwargs)
# example:
Class BoardPostForm(forms.ModelForm):
post_province=CustomChoiceField(label_field='province_japanese_name',queryset=Province.objects.all())
Comments