gpt4 book ai didi

python - 自定义插件上的默认子插件

转载 作者:行者123 更新时间:2023-12-01 01:24:18 28 4
gpt4 key购买 nike

我有一个名为 MultiColumnResponsive 的自定义插件,它接收列数作为参数,并仅接受 ColumnResponsive 插件作为子项。我想创建默认情况下嵌套为子级的 ColumnResponsive 插件,但我无法做到这一点。

这是我当前的代码:

cms_plugins.py

class MultiColumnResponsivePlugin(CMSPluginBase):
name = "Multi Column Responsive"
module = _("Containers")
model = MultiColumn
render_template = "plugin/multi-column-responsive/multi-column-responsive.html"
allow_children = True
child_classes = ["ColumnResponsivePlugin"]

def render(self, context, instance, placeholder):
context = super(MultiColumnResponsivePlugin, self).render(context, instance, placeholder)
return context

class ColumnResponsivePlugin(CMSPluginBase):
name = "Column Responsive"
module = _("Containers")
render_template = "plugin/column-responsive/column-responsive.html"
allow_children = True
parent_classes = ["MultiColumnResponsivePlugin"]

def render(self, context, instance, placeholder):
context = super(ColumnResponsivePlugin, self).render(context, instance, placeholder)
return context

models.py

class MultiColumn(CMSPlugin):
NUM_OF_COLUMNS = (
(1, '1'),
(2, '2'),
)
num_of_columns = models.IntegerField(default=1, choices=NUM_OF_COLUMNS)

这是我添加具有 2 列的 MultiColumnResponsive 插件时所需的结果:

enter image description here

编辑:经过几天的深入研究。我在 MultiColumnResponsivePlugin 类的 save_model 函数中添加了几行来实现它:

def save_model(self, request, obj, form, change):
response = super(MultiColumnResponsivePlugin, self).save_model(
request, obj, form, change
)
for x in range(int(form.cleaned_data['num_of_columns'])):
add_plugin(obj.placeholder, ColumnResponsivePlugin.__name__, obj.language, target=obj)
return response

最佳答案

你可以试试这个:

from django.forms import ModelForm, NumberInput
from cms.api import add_plugin

class MultiColumnResponsiveForm(ModelForm):
wanted_children = NumberInput()

class Meta:
model = MultiColumn
fields = '__all__'

class MultiColumnResponsivePlugin(CMSPluginBase):
name = "Multi Column Responsive"
module = _("Containers")
model = MultiColumn
render_template = "plugin/multi-column-responsive/multi-column-responsive.html"
allow_children = True
child_classes = ["ColumnResponsivePlugin"]
form = MultiColumnResponsiveForm

def save_model(self, request, obj, form, change):
wanted_children = form.cleaned_data['wanted_children']
super().save_model(request, obj, form, change)
self.extend_children(obj, wanted_children)

def extend_children(self, parent, wanted_children):
current_children = parent.get_num_children()
for _ in range(current_children, wanted_children):
child = add_plugin(parent.placeholder, ColumnResponsivePlugin,
parent.language, target=parent)
child.save()

对此的一些说明:

如果您需要临时值,例如 wanted_children,请使用表单,不要污染您的模型!

此代码片段来自 djangocms-cascade ,它使用类似的方法来实现相同的结果。

关于python - 自定义插件上的默认子插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492855/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com