Ticket #2445: choices_func_newforms-admin.patch

File choices_func_newforms-admin.patch, 2.5 KB (added by David Grant <davidgrant@…>, 17 years ago)

patch for newforms-admin branch. Just one line is different. Still doesn't work with inlines

  • django/db/models/base.py

     
    165165                val = field.get_default()
    166166            setattr(self, field.attname, val)
    167167
     168        for item in dir(self):
     169            if item.startswith('choices_for__'):
     170                choice_func = getattr(self,item)
     171                if callable(choice_func):
     172                    field_name = choice_func.__name__[len('choices_for__'):]
     173                    self._meta.get_field(field_name)._choices = choice_func
     174       
    168175        if kwargs:
    169176            for prop in kwargs.keys():
    170177                try:
  • django/db/models/fields/__init__.py

     
    88
    99from django.db import get_creation_module
    1010from django.db.models import signals
     11import django.db.models.query
    1112from django.dispatch import dispatcher
    1213from django.conf import settings
    1314from django.core import validators
     
    338339        "Returns a list of tuples used as SelectField choices for this field."
    339340        first_choice = include_blank and blank_choice or []
    340341        if self.choices:
    341             return first_choice + list(self.choices)
     342            if callable(self.choices):
     343                choices = self.choices()
     344            else:
     345                choices = self.choices
     346            # If choices is a QuerySet, convert into a tuple list ((pk,__unicode__),etc)
     347            if isinstance(choices, django.db.models.query.QuerySet):
     348                choices = [(x._get_pk_val(), smart_unicode(x)) for x in choices]
     349            return first_choice + list(choices)
     350           
    342351        rel_model = self.rel.to
    343352        if hasattr(self.rel, 'get_related_field'):
    344353            lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)]
     
    391400        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
    392401        if self.choices:
    393402            defaults['widget'] = forms.Select(choices=self.get_choices(include_blank=self.blank or not (self.has_default() or 'initial' in kwargs)))
     403            kwargs['queryset'] = self.choices()
    394404        if self.has_default():
    395405            defaults['initial'] = self.get_default()
    396406        defaults.update(kwargs)
Back to Top