Django MPTT tree as model filter in admin2019 Community Moderator ElectionHow do I do a not equal in Django queryset filtering?Exclusive Or ForeignKey in Django admin interfaceShow information of subclass in list_display djangodifferentiate null=True, blank=True in djangoRadio buttons in django adminCreate a new model which have all fields of currently existing modelHow to expose some specific fields of model_b based on a field of model_a?Django admin add custom filterHow to define Mode with generic ForeignKey in DjangoDjango Model Issue In Multilevel Inheritance.

Why do newer 737s use two different styles of split winglets?

Aluminum electrolytic or ceramic capacitors for linear regulator input and output?

A single argument pattern definition applies to multiple-argument patterns?

Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

Unable to evaluate Eigenvalues and Eigenvectors for a matrix (2)

How are passwords stolen from companies if they only store hashes?

combinatorics floor summation

What did “the good wine” (τὸν καλὸν οἶνον) mean in John 2:10?

Are relativity and doppler effect related?

Is it good practice to use Linear Least-Squares with SMA?

Are ETF trackers fundamentally better than individual stocks?

If I can solve Sudoku, can I solve the Travelling Salesman Problem (TSP)? If so, how?

How difficult is it to simply disable/disengage the MCAS on Boeing 737 Max 8 & 9 Aircraft?

Is "upgrade" the right word to use in this context?

I am confused as to how the inverse of a certain function is found.

Why does overlay work only on the first tcolorbox?

What is "focus distance lower/upper" and how is it different from depth of field?

Do the common programs (for example: "ls", "cat") in Linux and BSD come from the same source code?

How to explain that I do not want to visit a country due to personal safety concern?

This word with a lot of past tenses

Official degrees of earth’s rotation per day

Bacteria contamination inside a thermos bottle

How do I hide Chekhov's Gun?



Django MPTT tree as model filter in admin



2019 Community Moderator ElectionHow do I do a not equal in Django queryset filtering?Exclusive Or ForeignKey in Django admin interfaceShow information of subclass in list_display djangodifferentiate null=True, blank=True in djangoRadio buttons in django adminCreate a new model which have all fields of currently existing modelHow to expose some specific fields of model_b based on a field of model_a?Django admin add custom filterHow to define Mode with generic ForeignKey in DjangoDjango Model Issue In Multilevel Inheritance.










0















I have a model linked to a related model that is a Django MPTT tree model, I would like to be able to filter the first model using the Django MPTT tree in the admin console.



class Tenders(models.Model):
...
sector=models.ForeignKey(Sector, to_field='sectorId', null=True, blank=True,on_delete=models.CASCADE)
...

class Sector(MPTTModel):
name = models.CharField(max_length = 255)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,related_name='children')
sectorId = models.IntegerField(default=0,null=True,unique=True)


In the Django admin I would like to set up the filters for the Tenders model such that the Django-MPTT tree is the filter.



I have tried using the following:



class adminTenders(admin.ModelAdmin): 
def linkTo(self,obj):
return mark_safe("""<a href='' target="_blank" >Tender Link</a>""".format(obj.tenderLink))
linkTo.short_description=''

list_display=(
'title',
'linkTo',
'sector',
'region',
'repository',
'id',
)
list_filter=(
('sector', TreeRelatedFieldListFilter),
)

admin.site.register(Tenders,adminTenders)


However I get the following error when trying to run this and I cant figure it out:



 File "py36/lib/python3.6/site-packages/mptt/admin.py", line 314, in field_choices
mptt_level_indent * levels_dict[pk])
KeyError: 0


Any help would be greatly appreciated.



Edit 1: I think I have isolated the issue to the fact that my foreign key in Tenders to Sectors uses a to_field='sectorId instead of the default to link to the pk column. This had to be done for backwards compatibility to an old database scheme that I am stuck with.










share|improve this question




























    0















    I have a model linked to a related model that is a Django MPTT tree model, I would like to be able to filter the first model using the Django MPTT tree in the admin console.



    class Tenders(models.Model):
    ...
    sector=models.ForeignKey(Sector, to_field='sectorId', null=True, blank=True,on_delete=models.CASCADE)
    ...

    class Sector(MPTTModel):
    name = models.CharField(max_length = 255)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,related_name='children')
    sectorId = models.IntegerField(default=0,null=True,unique=True)


    In the Django admin I would like to set up the filters for the Tenders model such that the Django-MPTT tree is the filter.



    I have tried using the following:



    class adminTenders(admin.ModelAdmin): 
    def linkTo(self,obj):
    return mark_safe("""<a href='' target="_blank" >Tender Link</a>""".format(obj.tenderLink))
    linkTo.short_description=''

    list_display=(
    'title',
    'linkTo',
    'sector',
    'region',
    'repository',
    'id',
    )
    list_filter=(
    ('sector', TreeRelatedFieldListFilter),
    )

    admin.site.register(Tenders,adminTenders)


    However I get the following error when trying to run this and I cant figure it out:



     File "py36/lib/python3.6/site-packages/mptt/admin.py", line 314, in field_choices
    mptt_level_indent * levels_dict[pk])
    KeyError: 0


    Any help would be greatly appreciated.



    Edit 1: I think I have isolated the issue to the fact that my foreign key in Tenders to Sectors uses a to_field='sectorId instead of the default to link to the pk column. This had to be done for backwards compatibility to an old database scheme that I am stuck with.










    share|improve this question


























      0












      0








      0








      I have a model linked to a related model that is a Django MPTT tree model, I would like to be able to filter the first model using the Django MPTT tree in the admin console.



      class Tenders(models.Model):
      ...
      sector=models.ForeignKey(Sector, to_field='sectorId', null=True, blank=True,on_delete=models.CASCADE)
      ...

      class Sector(MPTTModel):
      name = models.CharField(max_length = 255)
      parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,related_name='children')
      sectorId = models.IntegerField(default=0,null=True,unique=True)


      In the Django admin I would like to set up the filters for the Tenders model such that the Django-MPTT tree is the filter.



      I have tried using the following:



      class adminTenders(admin.ModelAdmin): 
      def linkTo(self,obj):
      return mark_safe("""<a href='' target="_blank" >Tender Link</a>""".format(obj.tenderLink))
      linkTo.short_description=''

      list_display=(
      'title',
      'linkTo',
      'sector',
      'region',
      'repository',
      'id',
      )
      list_filter=(
      ('sector', TreeRelatedFieldListFilter),
      )

      admin.site.register(Tenders,adminTenders)


      However I get the following error when trying to run this and I cant figure it out:



       File "py36/lib/python3.6/site-packages/mptt/admin.py", line 314, in field_choices
      mptt_level_indent * levels_dict[pk])
      KeyError: 0


      Any help would be greatly appreciated.



      Edit 1: I think I have isolated the issue to the fact that my foreign key in Tenders to Sectors uses a to_field='sectorId instead of the default to link to the pk column. This had to be done for backwards compatibility to an old database scheme that I am stuck with.










      share|improve this question
















      I have a model linked to a related model that is a Django MPTT tree model, I would like to be able to filter the first model using the Django MPTT tree in the admin console.



      class Tenders(models.Model):
      ...
      sector=models.ForeignKey(Sector, to_field='sectorId', null=True, blank=True,on_delete=models.CASCADE)
      ...

      class Sector(MPTTModel):
      name = models.CharField(max_length = 255)
      parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,related_name='children')
      sectorId = models.IntegerField(default=0,null=True,unique=True)


      In the Django admin I would like to set up the filters for the Tenders model such that the Django-MPTT tree is the filter.



      I have tried using the following:



      class adminTenders(admin.ModelAdmin): 
      def linkTo(self,obj):
      return mark_safe("""<a href='' target="_blank" >Tender Link</a>""".format(obj.tenderLink))
      linkTo.short_description=''

      list_display=(
      'title',
      'linkTo',
      'sector',
      'region',
      'repository',
      'id',
      )
      list_filter=(
      ('sector', TreeRelatedFieldListFilter),
      )

      admin.site.register(Tenders,adminTenders)


      However I get the following error when trying to run this and I cant figure it out:



       File "py36/lib/python3.6/site-packages/mptt/admin.py", line 314, in field_choices
      mptt_level_indent * levels_dict[pk])
      KeyError: 0


      Any help would be greatly appreciated.



      Edit 1: I think I have isolated the issue to the fact that my foreign key in Tenders to Sectors uses a to_field='sectorId instead of the default to link to the pk column. This had to be done for backwards compatibility to an old database scheme that I am stuck with.







      django django-models django-admin django-mptt django-admin-filters






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 3:10







      Zexelon

















      asked Mar 6 at 20:44









      ZexelonZexelon

      5910




      5910






















          1 Answer
          1






          active

          oldest

          votes


















          0














          So it turns out this is a bug in the django-mptt code for the field_choices function in the TreeRelatedFieldListFilter class.



          To fix it I had to subclass and over ride that function to use the to_field that I had defined.



          Here is the custom code:



          class TreeRelatedForSectors(TreeRelatedFieldListFilter):
          # Modified from django-mptt code to fix to_field problem
          def field_choices(self, field, request, model_admin):
          mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
          language_bidi = get_language_bidi()
          initial_choices = field.get_choices(include_blank=False)
          pks = [pk for pk, val in initial_choices]
          models = field.related_model._default_manager.filter(sectorId__in=pks)
          levels_dict = model.sectorId: getattr(model, model._mptt_meta.level_attr) for model in models
          choices = []
          for pk, val in initial_choices:
          padding_style = ' style="padding-%s:%spx"' % (
          'right' if language_bidi else 'left',
          mptt_level_indent * levels_dict[pk])
          choices.append((pk, val, mark_safe(padding_style)))
          return choices





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55031861%2fdjango-mptt-tree-as-model-filter-in-admin%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            So it turns out this is a bug in the django-mptt code for the field_choices function in the TreeRelatedFieldListFilter class.



            To fix it I had to subclass and over ride that function to use the to_field that I had defined.



            Here is the custom code:



            class TreeRelatedForSectors(TreeRelatedFieldListFilter):
            # Modified from django-mptt code to fix to_field problem
            def field_choices(self, field, request, model_admin):
            mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
            language_bidi = get_language_bidi()
            initial_choices = field.get_choices(include_blank=False)
            pks = [pk for pk, val in initial_choices]
            models = field.related_model._default_manager.filter(sectorId__in=pks)
            levels_dict = model.sectorId: getattr(model, model._mptt_meta.level_attr) for model in models
            choices = []
            for pk, val in initial_choices:
            padding_style = ' style="padding-%s:%spx"' % (
            'right' if language_bidi else 'left',
            mptt_level_indent * levels_dict[pk])
            choices.append((pk, val, mark_safe(padding_style)))
            return choices





            share|improve this answer



























              0














              So it turns out this is a bug in the django-mptt code for the field_choices function in the TreeRelatedFieldListFilter class.



              To fix it I had to subclass and over ride that function to use the to_field that I had defined.



              Here is the custom code:



              class TreeRelatedForSectors(TreeRelatedFieldListFilter):
              # Modified from django-mptt code to fix to_field problem
              def field_choices(self, field, request, model_admin):
              mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
              language_bidi = get_language_bidi()
              initial_choices = field.get_choices(include_blank=False)
              pks = [pk for pk, val in initial_choices]
              models = field.related_model._default_manager.filter(sectorId__in=pks)
              levels_dict = model.sectorId: getattr(model, model._mptt_meta.level_attr) for model in models
              choices = []
              for pk, val in initial_choices:
              padding_style = ' style="padding-%s:%spx"' % (
              'right' if language_bidi else 'left',
              mptt_level_indent * levels_dict[pk])
              choices.append((pk, val, mark_safe(padding_style)))
              return choices





              share|improve this answer

























                0












                0








                0







                So it turns out this is a bug in the django-mptt code for the field_choices function in the TreeRelatedFieldListFilter class.



                To fix it I had to subclass and over ride that function to use the to_field that I had defined.



                Here is the custom code:



                class TreeRelatedForSectors(TreeRelatedFieldListFilter):
                # Modified from django-mptt code to fix to_field problem
                def field_choices(self, field, request, model_admin):
                mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
                language_bidi = get_language_bidi()
                initial_choices = field.get_choices(include_blank=False)
                pks = [pk for pk, val in initial_choices]
                models = field.related_model._default_manager.filter(sectorId__in=pks)
                levels_dict = model.sectorId: getattr(model, model._mptt_meta.level_attr) for model in models
                choices = []
                for pk, val in initial_choices:
                padding_style = ' style="padding-%s:%spx"' % (
                'right' if language_bidi else 'left',
                mptt_level_indent * levels_dict[pk])
                choices.append((pk, val, mark_safe(padding_style)))
                return choices





                share|improve this answer













                So it turns out this is a bug in the django-mptt code for the field_choices function in the TreeRelatedFieldListFilter class.



                To fix it I had to subclass and over ride that function to use the to_field that I had defined.



                Here is the custom code:



                class TreeRelatedForSectors(TreeRelatedFieldListFilter):
                # Modified from django-mptt code to fix to_field problem
                def field_choices(self, field, request, model_admin):
                mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
                language_bidi = get_language_bidi()
                initial_choices = field.get_choices(include_blank=False)
                pks = [pk for pk, val in initial_choices]
                models = field.related_model._default_manager.filter(sectorId__in=pks)
                levels_dict = model.sectorId: getattr(model, model._mptt_meta.level_attr) for model in models
                choices = []
                for pk, val in initial_choices:
                padding_style = ' style="padding-%s:%spx"' % (
                'right' if language_bidi else 'left',
                mptt_level_indent * levels_dict[pk])
                choices.append((pk, val, mark_safe(padding_style)))
                return choices






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 7 at 4:14









                ZexelonZexelon

                5910




                5910





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55031861%2fdjango-mptt-tree-as-model-filter-in-admin%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    1928 у кіно

                    Захаров Федір Захарович

                    Ель Греко