Django cms accessing extended property

回眸只為那壹抹淺笑 提交于 2019-12-08 07:41:02

问题


I've extended the Django cms Page model into ExtendedPage model and added page_image to it. How can I now acces the page_image property in a template.

I'd like to access the page_image property for every child object in a navigation menu... creating a menu with images...

I've extended the admin and I have the field available for editing (adding the picture)

from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pagemodel import Page
from django.conf import settings

class ExtendedPage(models.Model):   
    page = models.OneToOneField(Page, unique=True, verbose_name=_("Page"), editable=False, related_name='extended_fields')
    page_image = models.ImageField(upload_to=settings.MEDIA_ROOT, verbose_name=_("Page image"), blank=True)

Thank you!

BR


回答1:


request.current_page.extended_fields.page_image

should work if you are using < 2.4. In 2.4 they introduced a new two page system (published/draft) so you might need

request.current_page.publisher_draft.extended_fields.page_image

I usually write some middleware or a template processor to handle this instead of doing it repetitively in the template. Something like:

class PageOptions(object):
    def process_request(self, request):
        request.options = dict()
        if not request.options and request.current_page:
            extended_fields = None
            try:
                extended_fields = request.current_page.extended_fields
            except:
                try:
                    custom_settings = request.current_page.publisher_draft.extended_fields
                except:
                    pass
            if extended_fields:
                for field in extended_fields._meta.fields:
                    request.options[field.name] = getattr(extended_fields, field.name)
        return None

will allow you to simply do {{ request.options.page_image }}



来源:https://stackoverflow.com/questions/16849625/django-cms-accessing-extended-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!