wagtail AbstractImage, ParentalManyToManyField and ClusterableModel

天涯浪子 提交于 2021-02-07 17:33:06

问题


Using wagtail 2.1, django 2.0.3, python 3.6.4

I have the following (simplified) custom image model, linked to PhotoType and PhotoPlate via m2m relationships:

from wagtail.images.models import AbstractImage
from modelcluster.fields import ParentalManyToManyField
from modelcluster.models import ClusterableModel

class PhotoType(models.Model):
    title = models.CharField(verbose_name='Title', max_length=255, blank=False, null=False, default=None)

class PhotoPlate(models.Model):
    plate= models.CharField(verbose_name='Title', max_length=255, blank=False, null=False, default=None)

class Photo(AbstractImage):
    type = ParentalManyToManyField(PhotoType, help_text="Several are allowed.", blank=True)
    plate = ParentalManyToManyField(PhotoPlate, help_text="Several are allowed.", blank=True)

    class Meta:
        verbose_name = 'Photo'
        verbose_name_plural = 'Photos'

The PhotoType and PhotoPlate models are referenced via modeladmin_register(PhotoTypeModelAdmin) and modeladmin_register(PhotoPlateModelAdmin) in the local wagtail_hooks.py file.

All works fine after following the documentation.

Except for one thing: no matter how many items are selected in the multiple choice dropdowns that are rendered for the two fields type and plate, the corresponding m2m relationship is never saved. I found a few answers, but could get it to work by playing with the inheritance of the Photo class, for example: class CCAPhoto(ClusterableModel, AbstractImage).

Is there any way to add a ParentalManyToManyField to a custom image model? If so, what am I missing?

EDIT: When manually adding a relationship to the database, the right items are properly displayed on the wagtail admin form - -i.e., pre-selected on initial load.


回答1:


Rather than using ParentalManyToManyField, you should use a plain ManyToManyField here:

class Photo(AbstractImage):
    type = models.ManyToManyField(PhotoType, help_text="Several are allowed.", blank=True)
    plate = models.ManyToManyField(PhotoPlate, help_text="Several are allowed.", blank=True)

The ParentalManyToManyField and ParentalKey field types are designed for use in Wagtail's page editor (and related areas such as snippets), where multiple models need to be treated together as a single unit for previewing and version tracking. Wagtail's image and document models don't make use of this - they consist of a single model edited through an ordinary Django ModelForm, so ParentalManyToManyField and ParentalKey aren't necessary.



来源:https://stackoverflow.com/questions/51726614/wagtail-abstractimage-parentalmanytomanyfield-and-clusterablemodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!