【问题标题】:How to integrate a Django app with multiple forms in Django CMS as plugin?如何将 Django 应用程序与 Django CMS 中的多个表单集成为插件?
【发布时间】:2018-01-06 17:59:24
【问题描述】:

我按照tutorial 将我的 Django 应用程序集成到我的 Django CMS 网站中。

我的应用 Sale 有两个模型,OrderModel()CustomerModel(),它们都在 forms.py 中用于将某些字段传递给表单,如下所示:

class CustomerForm(forms.ModelForm):

    class Meta:
        model = CustomerModel
        fields = ['firstname', 'surname', 'company', 'email',]

class OrderForm(forms.ModelForm):

    class Meta:
        model = OrderModel
        fields = ['product', 'delivery_date',]

如教程中所述,在models.py 中我生成SalePluginModel 并在cms_plugins.py 中指定SalePluginPublisher 插件类,它负责为django CMS 提供渲染我的应用程序所需的信息,就像models.py

class SalePluginModel(CMSPlugin):

    title = models.CharField(u'title',
        blank=True,
        help_text=u'Optional. Title of the widget.',
        max_length=64,
    )

等等cms_plugins.py:

class SalePluginPublisher(CMSPluginBase):
    model = SalePluginModel  # model where plugin data are saved
    module = _("Sale")
    name = _("Sale Plugin")  # name of the plugin in the interface
    render_template = "sale/sale_plugin.html"
    form = '' # How to pass multiple model forms here? 

现在的问题是,只有一个表单类可以作为属性传递给CMSPluginBase。是否有可能在SalePluginPublisher 中包含两个表单类,或者一般来说,如何将我的应用程序与 Django CMS 中的两个模型和表单集成? 非常感谢您的帮助!

【问题讨论】:

    标签: python django django-forms django-cms


    【解决方案1】:

    所以澄清一下,您想向插件传递两个表单?如果是这样,您可以执行以下操作:

    class SalePluginPublisher(CMSPluginBase):
        model = SalePluginModel  # model where plugin data are saved
        module = _("Sale")
        name = _("Sale Plugin")  # name of the plugin in the interface
        render_template = "sale/sale_plugin.html"
    
        def render(self, context, instance, placeholder):
            context = super().render(context, instance, placeholder)
            context['customer_form'] = CustomerForm()
            context['order_form'] = OrderForm()
            return context
    

    如果您没有专用的 POST url,您也可以在 render 函数中处理 POST 响应。您只需要访问请求对象,例如self.request.POST.

    编辑:

    以上内容适用于 Python 3,若要与 Python 2 一起使用,您需要将渲染函数的第一行更改为:

    context = super(SalePluginPublisher, self).render(context, instance, placeholder)
    ...
    

    【讨论】:

    • 非常感谢。它起作用了,但是我必须将SalePluginPublisher, self 传递给super() 函数,所以context = super(SalePluginPublisher, self).render(context, instance, placeholder)。再次感谢!
    • 不用担心。我的示例适用于 Python 3,对于 Python 2,您需要按照上面所说的进行操作。我应该指定 :) 我现在已经编辑了答案。
    猜你喜欢
    • 2011-07-07
    • 2014-09-19
    • 2015-04-21
    • 2012-10-09
    • 2012-08-02
    • 2011-07-27
    • 2018-09-19
    • 2013-09-08
    • 2018-01-26
    相关资源
    最近更新 更多