2016-07-14 50 views
0

我想爲Django CMS創建一個自定義插件。正如guide顯示的那樣,我創建了一些示例。但是現在我們的目標是創建一個可以從(mysql)數據庫獲取數據的插件。它會加載屬於菜單的所有標題,因爲我想要與目錄類似。Django CMS自定義插件從cms_title加載數據

要從自定義模型中獲取數據,代碼是這樣的:

  • models.py:

    from cms.models.pluginmodel import CMSPlugin 
    
    from django.db import models 
    
    class Hello(CMSPlugin): 
    
        guest_name = models.CharField(max_length=50, default='Guest') 
    
  • cms_plugins.py

來自cms.plugin_ba的

SE進口CMSPluginBase

from cms.plugin_pool import plugin_pool 

from django.utils.translation import ugettext_lazy as _ 
from .models import Hello 

class HelloPlugin(CMSPluginBase): 
    model = Hello 
    name = _("Hello Plugin") 
    render_template = "hello_plugin.html" 
    cache = False 

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

plugin_pool.register_plugin(HelloPlugin) 

但作爲cms_title默認屬於Django的CMS,哪些選項是可能的嗎?我在哪裏可以找到名稱爲Title的CMS模型的定義?將它設置爲CMSPlugin實例會是一個糟糕的方法嗎?

回答

0

好吧,經過幾個小時的這種情況下,我終於成功地解決了我的問題。

首先,用CMS模型和參數標題(在db:cms_title中)回答問題的部分。創建一個FK到CMS標題的新模型是正確的方法。 在models.py

class TitlePlugin(CMSPlugin): 
     title = models.ForeignKey(Title) 

至於未來,你需要將其導入到cms_plugins.py,所以它看起來是這樣的:

from .models import TitlePlugin 

class MyTitlePluginClass(CMSPluginBase): 
    model = TitlePlugin 
    render_template = "titles.html" 
    cache = False 

正如你看到的,我們加載的模型是TitlePlugin,我們在models.py中定義(其中FK爲原始cms_title)。

而現在,使其:

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

    context = super(MyTitlePluginClass, self).render(context, instance, placeholder) 
    return context 

但我的目標是將其加載到模板「目錄」的目的,對不對?所以我不得不改變一些事情。

我刪除models.py內容

新cms_plugins.py有修改過(沒有必要!): 第一:

from cms.models.pagemodel import Page 
#we import the Page model 

和更新類:

class MyTitlePluginClass(CMSPluginBase): 
    model = CMSPlugin 
    render_template = "titles.html" 
    cache = False 

def render(self, context, instance, placeholder): 
    pages = Page.objects.filter(in_navigation=True, publisher_is_draft=False) 

    #context = { 
    #'pages' : pages, 
    #} 
    # edit: append to 'pages' existing list! 
    context['pages'] = pages 

    context = super(MyTitlePluginClass, self).render(context, instance, placeholder) 
    return context 

plugin_pool.register_plugin(MyTitlePluginClass) 

而在模板中,我們只需使用for循環01打印它titles.html

{% for page in pages %} 
<div class="panel callout "> 
    {{ page }} 
</div> 
{% endfor %} 
相關問題