Login

CustomChoiceField, Selectable label field version of ModelChoiceField

Author:
mauro
Posted:
March 14, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

The problem

ModelChoiceField always uses unicode or str to fill the labels. I needed to dynamically select which field to use for the labels.

The solution My approach copies a lot from this blog with some modifications to make it more dynamic. There are some proposals to fix on this Ticket #4620

How to use Include the code on your forms.py (or whatever you are using) and use the CustomChoiceField with the extra argument label_field instead of ModelChoiceField.

Hope it helps someone.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.