如何在Wagtail Admin中添加多对多字段?

时间:2018-12-17 03:12:52

标签: django wagtail

我试图为每个页面上包含的Wagtail网站设置页脚,但我想提供链接列表(电话,电子邮件,社交媒体)。如果在没有panel = [...]的情况下尝试下面的代码,我可以看到它的正常工作,但是我无法添加任何项目:

enter image description here

from wagtail.contrib.settings.models import BaseSetting, register_setting
from django import forms

class ContactInfo(models.Model):
    CONTACT_CHOICES = (
        ('fas fa-phone', 'Phone'),
        ('fas fa-envelope', 'Email'),
        ('fab fa-facebook-f', 'Facebook'),
        ('fa-instagram', 'Instagram'),
        ('fab fa-linkedin', 'LinkedIn'),
        ('fab fa-twitter', 'Twitter'),
        ('fab fa-pinterest', 'Pinterest'),
        ('fab fa-github', 'GitHub'),
        ('fab fa-gitlab', 'GitLab'),
    )

    contact_type = models.CharField(choices=CONTACT_CHOICES, max_length=50)
    contact_info = models.CharField(max_length=50)
    info_prefix = models.CharField(max_length=10, editable=False)

    def save(self, *args, **kwargs):
        if self.contact_type == 'Phone':
            self.info_prefix = 'tel:'
        elif self.contact_type == 'Email':
            self.info_prefix = 'mailto:'
        else:
            self.info_prefix = ''


@register_setting
class Contact(BaseSetting):
    contact = models.ManyToManyField(ContactInfo)

    panels = [
        FieldPanel('contact', widget=forms.CheckboxSelectMultiple)
    ]

是否有要向M2M字段添加项目的内容?有办法在Wa设置中列出项目吗?有没有更简单的方法来制作在每个页面上自动呈现的页脚?

1 个答案:

答案 0 :(得分:4)

每个ContactInfo项目(大概)都属于一个Contact,因此这是一对多关系而不是多对多关系。 (在这种情况下,多对多关系意味着您有一个ContactInfo项的共享池,这些项以前是通过其他视图定义的,并且您正在选择要附加到当前Contact的项)

在Wa中,将使用ParentalKey上的ContactInfo指向相应的Contact进行定义,并用InlinePanel进行渲染。 (有关示例,请参见Wagtail教程中的gallery image示例。)

from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel
from wagtail.core.models import Orderable
from wagtail.contrib.settings.models import BaseSetting, register_setting
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel

class ContactInfo(Orderable):
    CONTACT_CHOICES = (
        # ...
    )

    contact = ParentalKey('Contact', on_delete=models.CASCADE, related_name='contact_links')
    contact_type = models.CharField(choices=CONTACT_CHOICES, max_length=50)
    contact_info = models.CharField(max_length=50)
    # info_prefix handling omitted here for brevity

    panels = [
        FieldPanel('contact_type'),
        FieldPanel('contact_info'),
    ]


@register_setting
class Contact(BaseSetting, ClusterableModel):
    panels = [
        InlinePanel('contact_links', label="Contact")
    ]