Django-CMS子插件显示来自数据库表

时间:2016-01-06 17:24:17

标签: python django django-cms

我有两个插件ProductSelector(父)和SpecificationSelector(子)。我想设置子项,以便在将其添加到父项时,显示的规范是产品(父项)的唯一规格。现在它从表中提取所有规格。这些行让我过滤数据以获得我想要的。

编辑:我发现我在代码中修复了一个错误。我有PluginBase名称与模型相同。这允许我在子节点中使用ProductSelector.objects.get(cmsplugin_ptr = instance.parent)来获取父实例。我仍然需要弄清楚如何将过滤的规范列表传递给“PluginAdmin接口”

    product = ProductSelector.objects.get(cmsplugin_ptr=instance.parent)
    specification = Specifications.objects.filter(product_name__product_name__iexact = product.product_name)

但是,我还没想出如何将过滤后的列表发送到插件管理界面。

class ProductSelectorPlugin(CMSPluginBase):
    model = ProductSelector
    name = "Product Selector"
    render_template = "product_selector.html"
    allow_children = True
    child_classes = ['SpecificationSelectorPlugin'] 

    def render(self, context, instance, placeholder):

        context['instance'] = instance
        return context

plugin_pool.register_plugin(ProductSelectorPlugin)

class SpecificationSelectorPlugin(CMSPluginBase):
    model = SpecificationSelector   
    render_template = "specification_selector.html"
    formfield_overrides = {models.ManyToManyField: {'widget': CheckboxSelectMultiple},}

    def render(self, context, instance, placeholder):
        product = ProductSelector.objects.get(cmsplugin_ptr=instance.parent)
        specification = Specifications.objects.filter(product_name__product_name__iexact = product.product_name)
        context['instance'] = instance
        return context

plugin_pool.register_plugin(SpecificationSelectorPlugin)

models.py

class ProductSelector(CMSPlugin):
    product_name = models.ForeignKey(Product, help_text = "Select the product you want to place")
    new_product = models.BooleanField(blank=True)


class SpecificationSelector(CMSPlugin):
    specification = models.ManyToManyField(Specifications, blank=True)

    def __unicode__(self): 
        return unicode(self.specification)

以下是占位符中Django-cms插件的屏幕截图。目前它显示的是表格中的所有规格,但我只是希望它是该特定产品的规格。

http://imgur.com/3R1LobC

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

来自CMSPluginBase

ModelAdmin inhertis意味着您可以覆盖添加和修改插件时呈现的表单。

所以你可以像这样创建一个ModelForm子类:

class SpecificationSelectorPluginForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(SpecificationSelectorPluginForm, self).__init__(*args, **kwargs)
        if self.instance.parent_id:
            # Assume that the parent is a product instance
            parent_plugin = self.instance.parent
            product = parent_plugin.get_plugin_instance()[0]

            if product:
                # It's possible that product is an orphan plugin.

                specifications = Specifications.objects.filter(
                    product_name__product_name__iexact=product.product_name)
                self.fields['specification'].queryset = specifications

然后更改您的SpecificationSelectorPlugin以使用此表单,如下所示:

class SpecificationSelectorPlugin(CMSPluginBase):
    form = SpecificationSelectorPluginForm

以上只有在规范插件是产品插件的直接子项时才有效。