2010-09-17 19 views
2

我有一個表格,ModelMultipleChoiceField到類別列表。 我想使用Category.group字段對類別進行分組。如何添加optgroups到django ModelMultipleChoiceField?

我以爲通過改變字段。 choices在init函數就會使的伎倆

class CategoriesField(forms.ModelMultipleChoiceField): 
    def __init__(self, queryset, **kwargs): 
     super(forms.ModelMultipleChoiceField, self).__init__(queryset, **kwargs) 
     self.queryset = queryset.select_related() 
     self.to_field_name=None 

     group = None 
     list = [] 
     self.choices = [] 

     for category in queryset: 
      if not group: 
       group = category.group 

      if group != category.group: 
       self.choices.append((group.title, list)) 
       group = category.group 
       list = [(category.id, category.name)] 
      else: 
       list.append((category.id, category.name)) 
     try: 
      self.choices.append((group.title, list)) 
     except: 
      pass 

ModelChoiceIterator還是抹去self.choices信息被在__init__功能設置。

我該如何做到這一點?

回答

0

事實上,它正在像我剛纔解釋,但不要忘了,部分:

class ProfilForm(ModelForm): 
    categories = CategoriesField(queryset=Category.objects.all().order_by('group'), label=_(u'Catégories')) 
0

我發現這個問題/答案有幫助,但改變了代碼了很多。上述代碼的問題在於,它只生成一次列表,然後緩存(查詢集僅使用一次)。我的代碼是針對「配置文件」(又名作者)排序的「文章」對象,但任何人都應該能夠對其進行修改以供其使用。它每次都使用一個新的查詢集,因此它在沒有重新啓動的情況下進行更新(除非您將cache_choices=True傳遞給ArticleMultipleChoiceField然後將其緩存)。

class ArticleChoiceIterator(forms.models.ModelChoiceIterator): 
    def __iter__(self): 
     if self.field.empty_label is not None: 
      yield ("", self.field.empty_label) 
     if self.field.cache_choices: 
      if self.field.choice_cache is None: 
       last_profile = None 
       self.field.choice_cache = [] 
       for article in self.queryset.all(): 
        if last_profile != article.profile: 
         last_profile = article.profile 
         article_list = [] 
         self.field.choice_cache.append((article.profile.name, article_list)) 
        article_list.append(self.choice(article)) 
      for choice in self.field.choice_cache: 
       yield choice 
     else: 
      last_profile = None 
      article_choices = [] 
      for article in self.queryset.all(): 
       if last_profile != article.profile: 
        if article_choices: 
         yield (getattr(last_profile, 'name', ''), article_choices) 
        last_profile = article.profile 
        article_choices = [] 
       article_choices.append(self.choice(article)) 
      if article_choices: 
       yield (getattr(last_profile, 'name', ''), article_choices) 


class ArticleMultipleChoiceField(forms.ModelMultipleChoiceField): 
    # make sure queryset is ordered by profile first! 
    def __init__(self, queryset, **kwargs): 
     super(ArticleMultipleChoiceField, self).__init__(queryset, **kwargs) 
     self.queryset = queryset.select_related('profile') 
     self._choices = ArticleChoiceIterator(self) 


class PackageForm(forms.ModelForm): 
    articles = ArticleMultipleChoiceField(
     queryset=Article.objects.order_by('profile__name', 'title') 
    ) 
相關問題