如何基于Page父级限制Django-CMS template_choices

时间:2018-09-14 16:00:59

标签: django-cms

这个问题可以用更广泛的问题来解决:“如何用外部属性替换python 2.7属性”,但是也许有Django-CMS的方式来实现,所以我问:

我试图基于其父级来限制Django-CMS'(v3.4.x)页面的模板选择,因此,我想到了使用功能覆盖它的template_choices,但我看到了在Django-CMS的Page模型中,它是在创建时加载的,就像这样:

@python_2_unicode_compatible
class Page(...):
...
TEMPLATE_DEFAULT = get_cms_setting('TEMPLATES')[0][0]
template_choices = [(x, _(y)) for x, y in get_cms_setting('TEMPLATES')]
...

无法修改get_cms_settins,但是我确实需要更改TEMPLATE_DEFAULTtemplate_choices,以便它们具有我想要的适当值。由于我还是Django和Python的新手,所以我的问题是在哪里如何该怎么做?

1 个答案:

答案 0 :(得分:0)

我的第一个尝试是在models.py上做类似的事情:

@property
def template_choices(self):
    from cms.utils import get_cms_setting
    templates = [(x, _(y)) for x, y in get_cms_setting('TEMPLATES')]
    if self.parent:
        if self.parent.template == 'parent_a.html':
            templates = [('child_A.html', _('Child A'))]
        elif self.parent.template == 'parent_b.html':
            templates = [('child_b.html', _('Child B'))]
        else:
            templates = [('fullwidth.html', _('Fullwidth'))]
    else:
        templates = [('home_page.html', _('Homepage')), 
                     ('parent_a.html', _('Parent A')), 
                     ('parent_b.html', _('Parent B'))]
    return templates


@property
def template_default(self):
    return self.template_choices[0][0]


Page.template_choices = template_choices
Page.TEMPLATE_DEFAULT = template_default

如果我尝试检查Page的任何实例,那么 会正确设置这些字段,但是当我尝试编辑任何页面并单击Page> Templates菜单时,所有模板可供选择,因此template_choicesTEMPLATE_DEFAULT属性似乎被忽略了。检查pagemodel.py似乎可以证实这一点,因为get_templateget_template_name方法使用get_cms_setting('TEMPLATES')而不是那些字段。同样在cms_toolbars.py# templates menu部分的get_cms_setting('TEMPLATES')而非似乎是罪魁祸首的self.page.template_choices。因此,这个问题变成了一个故障单:https://github.com/divio/django-cms/issues/6520