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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved