PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 19, 2022

[FIXED] How to change Wagtail admin Tag wiget to select?

 October 19, 2022     admin, python, wagtail     No comments   

Issue

I have tags model:

class MediaTag(TagBase):
free_tagging = False
color = models.CharField(
    _("Tag color"),
    max_length=7,
    choices=MEDIA_TAG_COLOR_CHOICES
)
site = models.ForeignKey(
    'wagtailcore.Site',
    null=True,
    blank=True,
    on_delete=models.SET_NULL,
    related_name='+'
)


class MediaTagItem(ItemBase):
    tag = models.ForeignKey(
        MediaTag, related_name="tagged_media", on_delete=models.CASCADE
    )
    content_object = ParentalKey(
        'MediaPage',
        on_delete=models.CASCADE,
        related_name='tagged_items'
    )

class MediaPage(AbstractNewsPage, index.Indexed):
    tags = ClusterTaggableManager(through=MediaTagItem, blank=False)
    ...

I need to change MediaPage admin widget for the tags feild to select. And set options for it with tags for the same site as the page. I can change the widget using the register_form_field_override function, but how do I pass choises there?


Solution

It works, but only with single word tags:

from django import forms
from wagtail.admin.panels import FieldPanel
from django.apps import apps

class TagSelectPanel(FieldPanel):

    def get_form_options(self, *args):
        options = super().get_form_options(*args)
        options["widgets"] = {
            self.field_name: forms.widgets.Select(),
        }
        return options

    def get_bound_panel(self, instance, *args, **kwargs):
        panel = super().get_bound_panel(*args, **kwargs)
        model = apps.get_model('news', 'MediaTag')
        choices_queryset = model.objects.all()
        field = panel.form.fields[self.field_name]
        field.widget.choices = [
            (item.name, item.name) for item in choices_queryset
        ]
        return panel


class MediaPage(AbstractNewsPage, index.Indexed):
    ...
    content_panels = AbstractNewsPage.content_panels + [
        TagSelectPanel('tags'),
        ...
    ]


Answered By - Nikolay
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing