CustomChoiceField, Selectable label field version of ModelChoiceField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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())

 

More like this

  1. Read only form & model field by StanislavKraev 2 years, 9 months ago
  2. ModelChoiceField with choice groups for recursive relationships by estecb 3 months ago
  3. Render dynamically assigned fields in a template by rubic 7 years, 1 month ago
  4. ModelChoiceField with optiongroups by anentropic 4 years, 1 month ago
  5. CustomImageField for Django 1.0 alpha by hanksims 5 years, 8 months ago

Comments

(Forgotten your password?)