2017-09-11 14 views
0

django-mptt TreeNodeChoiceField은 들여 쓰기 선택 옵션을 제공하지만 django-autocomplete-light을 사용하여 결과를 필터링 할 수 있습니다. 그러나 ModelSelect2 위젯은 들여 쓰기를 제거하는 렌더링 된 HTML을 덮어 씁니다.django-mptt TreeNodeChoiceField와 django-autocomplete-light ModelSelect2 위젯을 결합하십시오.

두 가지를 결합하고 싶습니다. 내가 어떻게이 일을 성취 할 수 있었는지 아는가?

models.py :

class Foo(MPTTModel): 
    name = models.CharField(max_length=50) 
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) 

    class MPTTMeta: 
     order_insertion_by = ['name'] 

forms.py :

class FooForm(forms.ModelForm): 
    parent = TreeNodeChoiceField(queryset=Foo.objects.all(), widget=autocomplete.ModelSelect2(url='foo-autocomplete')) 

    class Meta: 
     model = Foo 
     fields = ('name', 'parent',) 

답변

0

여기 내 솔루션을 떠날거야 경우 다른 사람이 동일한 달성하려고합니다.

django-mptt 소스 코드와 django-autocomplete-light 예제를 살펴본 후 select 옵션의 표시 텍스트를 무시할 수 있다는 것을 알게되었습니다. 또한 django-mptt는 올바른 들여 쓰기를 삽입하기 위해 노드의 레벨을 사용합니다. 내 모델과 양식은 동일하게 유지됩니다. 방금 내 자동 완성보기의 get_result_label() 메소드를 재정의해야했습니다.

from mptt.settings import DEFAULT_LEVEL_INDICATOR 

class FooAutocomplete(autocomplete.Select2QuerySetView): 
    def get_result_label(self, item): 
     level_indicator = DEFAULT_LEVEL_INDICATOR * item.level 
     return level_indicator + ' ' + str(item) 

    def get_queryset(self): 
     qs = Foo.objects.all() 
     if self.q: 
      qs = qs.filter(name__istartswith=self.q) 
     return qs