Example #1
0
class TestPageImageTags(TestCase):
    def setUp(self):
        self.p = Page(title='test')
        self.p.save()

    def setUpTemplate(self):
        self.tmpl = Template(u'{% load pageimage_tags %}This will point to image \'{% pageimage \'BACKGROUND\' %}\'.')
        self.c = Context({'page': self.p})

    def test_simpletemplate_empty(self):
        self.setUpTemplate()
        tmplout = self.tmpl.render(self.c)
        self.assertTrue('\'\'' in tmplout)

    def test_simpletemplate_default(self):
        self.setUpTemplate()
        DefaultImage.objects.create(type='BACKGROUND', file='defaultback.jpg')
        self.assertTrue(
            '\'/static/media/defaultback.jpg\'' in self.tmpl.render(self.c)
        )

    def test_simpletemplate_specific(self):
        self.setUpTemplate()
        PageImage.objects.create(page=self.p, type='BACKGROUND', file='back.jpg')
        self.assertTrue(
            '\'/static/media/back.jpg\'' in self.tmpl.render(self.c)
        )
Example #2
0
    def get_content_models(cls):
        """
        Return all Page subclasses that are admin registered, ordered
        based on the ``ADD_PAGE_ORDER`` setting.
        """
        models = []
        for model in Page.get_content_models():
            try:
                admin_url(model, "add")
            except NoReverseMatch:
                continue
            else:
                setattr(model, "meta_verbose_name", model._meta.verbose_name)
                setattr(model, "add_url", admin_url(model, "add"))
                models.append(model)
        order = [name.lower() for name in settings.ADD_PAGE_ORDER]

        def sort_key(page):
            name = "%s.%s" % (page._meta.app_label, page._meta.object_name)
            unordered = len(order)
            try:
                return (order.index(name.lower()), "")
            except ValueError:
                return (unordered, page.meta_verbose_name)

        return sorted(models, key=sort_key)
Example #3
0
    def get_content_models(cls):
        """
        Return all Page subclasses that are admin registered, ordered
        based on the ``ADD_PAGE_ORDER`` setting.
        """
        models = []
        for model in Page.get_content_models():
            try:
                admin_url(model, "add")
            except NoReverseMatch:
                continue
            else:
                setattr(model, "meta_verbose_name", model._meta.verbose_name)
                setattr(model, "add_url", admin_url(model, "add"))
                models.append(model)
        order = [name.lower() for name in settings.ADD_PAGE_ORDER]

        def sort_key(page):
            name = "%s.%s" % (page._meta.app_label, page._meta.object_name)
            unordered = len(order)
            try:
                return (order.index(name.lower()), "")
            except ValueError:
                return (unordered, page.meta_verbose_name)
        return sorted(models, key=sort_key)
Example #4
0
def get_page_types():
    qry = None
    for m in Page.get_content_models():
        q = models.Q(app_label=m._meta.app_label, model=m._meta.model_name)
        qry = qry | q if qry else q

    return qry
Example #5
0
def models_for_pages(*args):
    """
    Create a select list containing each of the models that subclass the
    ``Page`` model.
    """
    page_models = []
    print Page.get_content_models()
    for model in Page.get_content_models():
        try:
            admin_url(model, "add")
        except NoReverseMatch:
            continue
        else:
            setattr(model, "name", model._meta.verbose_name)
            setattr(model, "add_url", admin_url(model, "add"))
            page_models.append(model)
    return page_models
Example #6
0
    def setUp(self):
        self.user = User(username="******")
        self.user.set_password("asdf")
        self.user.save()

        p = os.path.dirname(os.path.abspath(__file__))

        icon = open(os.path.join(p, "test_files/icon.psd"))
        f_icon = File(icon)

        self.button = HybridButton(
            name="Testbutton",
            user=self.user,
            icon=f_icon,
        )
        self.button.save()

        page = Page(status='2', description="buttonizer", title="Buttonizer")
        page.save()
Example #7
0
def get_page_with_children(context, page_slug):
    try:
        page = Page.objects.get(slug=page_slug)
        page = page.get_content_model()
    except:
        page = None
    else:
        rel = [m.__name__.lower() for m in Page.get_content_models()]
        page.published_children = Page.objects.published().filter(
            parent=page).order_by('_order').select_related(*rel)
    return page
Example #8
0
def autodiscover():
    autodiscover_modules('admin',register_to=site)

    for m in Page.get_content_models():
        try:
            adm = site._registry[m]
        except KeyError:
            continue

        if not isinstance(adm, PageAdmin) and isinstance(adm, mezz_PageAdmin):
            if site.safe_unregister(m):
                site.register(m, PageAdmin)

    site.lazy_registration()
Example #9
0
def get_page_children(context, page=None):
    children = None
    if isinstance(page, str):
        page = Page.objects.get(slug=page)

    if not page and 'page' in context:
        page = context['page']

    if page:
        rel = [m.__name__.lower() for m in Page.get_content_models()]
        children = Page.objects.published().filter(
            parent=page).order_by('_order').select_related(*rel)

    return children
Example #10
0
def models_for_pages(*args):
    """
    Create a select list containing each of the models that subclass the
    ``Page`` model.
    """
    page_models = []
    for model in Page.get_content_models():
        try:
            admin_url(model, "add")
        except NoReverseMatch:
            continue
        else:
            setattr(model, "name", model._meta.verbose_name)
            setattr(model, "add_url", admin_url(model, "add"))
            page_models.append(model)
    return page_models
Example #11
0
def page_menu(context, token):
    """
    Return a list of child pages for the given parent, storing all
    pages in a dict in the context when first called using parents as keys
    for retrieval on subsequent recursive calls from the menu template.
    """
    # First arg could be the menu template file name, or the parent page.
    # Also allow for both to be used.
    template_name = None
    parent_page = None
    parts = token.split_contents()[1:]
    for part in parts:
        part = Variable(part).resolve(context)
        if isinstance(part, unicode):
            template_name = part
        elif isinstance(part, Page):
            parent_page = part
    if template_name is None:
        try:
            template_name = context["menu_template_name"]
        except KeyError:
            error = "No template found for page_menu in: %s" % parts
            raise TemplateSyntaxError(error)
    context["menu_template_name"] = template_name
    if "menu_pages" not in context:
        try:
            user = context["request"].user
            slug = context["request"].path
        except KeyError:
            user = None
            slug = ""
        num_children = lambda id: lambda: len(context["menu_pages"][id])
        has_children = lambda id: lambda: num_children(id)() > 0
        published = Page.objects.published(for_user=user)
        if slug == admin_url(Page, "changelist"):
            related = [m.__name__.lower() for m in Page.get_content_models()]
            published = published.select_related(*related)
        else:
            published = published.select_related(depth=2)
        # Store the current page being viewed in the context. Used
        # for comparisons in page.set_menu_helpers.
        if "page" not in context:
            try:
                context["_current_page"] = published.get(slug=slug)
            except Page.DoesNotExist:
                context["_current_page"] = None
        elif slug:
            context["_current_page"] = context["page"]
        # Some homepage related context flags. on_home is just a helper
        # indicated we're on the homepage. has_home indicates an actual
        # page object exists for the homepage, which can be used to
        # determine whether or not to show a hard-coded homepage link
        # in the page menu.
        home = home_slug()
        context["on_home"] = slug == home
        context["has_home"] = False
        # Maintain a dict of page IDs -> parent IDs for fast
        # lookup in setting page.is_current_or_ascendant in
        # page.set_menu_helpers.
        context["_parent_page_ids"] = {}
        pages = defaultdict(list)
        for page in published.order_by("_order"):
            page.set_helpers(context)
            context["_parent_page_ids"][page.id] = page.parent_id
            setattr(page, "num_children", num_children(page.id))
            setattr(page, "has_children", has_children(page.id))
            pages[page.parent_id].append(page)
            if page.slug == home:
                context["has_home"] = True
        context["menu_pages"] = pages
    # ``branch_level`` must be stored against each page so that the
    # calculation of it is correctly applied. This looks weird but if we do
    # the ``branch_level`` as a separate arg to the template tag with the
    # addition performed on it, the addition occurs each time the template
    # tag is called rather than once per level.
    context["branch_level"] = 0
    parent_page_id = None
    if parent_page is not None:
        context["branch_level"] = getattr(parent_page, "branch_level", 0) + 1
        parent_page_id = parent_page.id

    # Build the ``page_branch`` template variable, which is the list of
    # pages for the current parent. Here we also assign the attributes
    # to the page object that determines whether it belongs in the
    # current menu template being rendered.
    context["page_branch"] = context["menu_pages"].get(parent_page_id, [])
    context["page_branch_in_menu"] = False
    for page in context["page_branch"]:
        page.in_menu = page.in_menu_template(template_name)
        page.num_children_in_menu = 0
        if page.in_menu:
            context["page_branch_in_menu"] = True
        for child in context["menu_pages"].get(page.id, []):
            if child.in_menu_template(template_name):
                page.num_children_in_menu += 1
        page.has_children_in_menu = page.num_children_in_menu > 0
        page.branch_level = context["branch_level"]
        page.parent = parent_page

        # Prior to pages having the ``in_menus`` field, pages had two
        # boolean fields ``in_navigation`` and ``in_footer`` for
        # controlling menu inclusion. Attributes and variables
        # simulating these are maintained here for backwards
        # compatibility in templates, but will be removed eventually.
        page.in_navigation = page.in_menu
        page.in_footer = not (not page.in_menu and "footer" in template_name)
        if page.in_navigation:
            context["page_branch_in_navigation"] = True
        if page.in_footer:
            context["page_branch_in_footer"] = True

    t = get_template(template_name)
    return t.render(Context(context))
Example #12
0
def page_menu(context, token):
    """
    Return a list of child pages for the given parent, storing all
    pages in a dict in the context when first called using parents as keys
    for retrieval on subsequent recursive calls from the menu template.
    """
    # First arg could be the menu template file name, or the parent page.
    # Also allow for both to be used.
    template_name = None
    parent_page = None
    parts = token.split_contents()[1:]
    for part in parts:
        part = Variable(part).resolve(context)
        if isinstance(part, unicode):
            template_name = part
        elif isinstance(part, Page):
            parent_page = part
    if template_name is None:
        try:
            template_name = context["menu_template_name"]
        except KeyError:
            error = "No template found for page_menu in: %s" % parts
            raise TemplateSyntaxError(error)
    context["menu_template_name"] = template_name
    if "menu_pages" not in context:
        try:
            user = context["request"].user
            slug = context["request"].path
        except KeyError:
            user = None
            slug = ""
        num_children = lambda id: lambda: len(context["menu_pages"][id])
        has_children = lambda id: lambda: num_children(id)() > 0
        published = Page.objects.published(for_user=user)
        if slug == admin_url(Page, "changelist"):
            related = [m.__name__.lower() for m in Page.get_content_models()]
            published = published.select_related(*related)
        else:
            published = published.select_related(depth=2)
        # Store the current page being viewed in the context. Used
        # for comparisons in page.set_menu_helpers.
        if "page" not in context:
            try:
                context["_current_page"] = published.get(slug=slug)
            except Page.DoesNotExist:
                context["_current_page"] = None
        elif slug:
            context["_current_page"] = context["page"]
        # Maintain a dict of page IDs -> parent IDs for fast
        # lookup in setting page.is_current_or_ascendant in
        # page.set_menu_helpers.
        context["_parent_page_ids"] = {}
        pages = defaultdict(list)
        for page in published.order_by("_order"):
            page.set_helpers(context)
            context["_parent_page_ids"][page.id] = page.parent_id
            setattr(page, "num_children", num_children(page.id))
            setattr(page, "has_children", has_children(page.id))
            pages[page.parent_id].append(page)
        context["menu_pages"] = pages
        context["on_home"] = slug == reverse("home")
    # ``branch_level`` must be stored against each page so that the
    # calculation of it is correctly applied. This looks weird but if we do
    # the ``branch_level`` as a separate arg to the template tag with the
    # addition performed on it, the addition occurs each time the template
    # tag is called rather than once per level.
    context["branch_level"] = 0
    parent_page_id = None
    if parent_page is not None:
        context["branch_level"] = getattr(parent_page, "branch_level", 0) + 1
        parent_page_id = parent_page.id

    context["page_branch"] = context["menu_pages"].get(parent_page_id, [])
    context["page_branch_in_menu"] = False
    for page in context["page_branch"]:
        # footer/nav for backward compatibility.
        page.in_footer = page.in_navigation = page.in_menu = True
        for i, l, t in settings.PAGE_MENU_TEMPLATES:
            if not unicode(i) in page.in_menus and t == template_name:
                page.in_navigation = page.in_menu = False
                if "footer" in template_name:
                    page.in_footer = False
                break
        if page.in_menu:
            context["page_branch_in_menu"] = True
    # Backwards compatibility
    context['page_branch_in_navigation'] = context["page_branch_in_menu"]
    context['page_branch_in_footer'] = (context["page_branch_in_menu"]
                                        and template_name
                                        == "pages/menu/footer.html")

    for i, page in enumerate(context["page_branch"]):
        context["page_branch"][i].branch_level = context["branch_level"]
        context["page_branch"][i].parent = parent_page
    t = get_template(template_name)
    return t.render(context)
Example #13
0
def page_menu(context, token):
    """
    Return a list of child pages for the given parent, storing all
    pages in a dict in the context when first called using parents as keys
    for retrieval on subsequent recursive calls from the menu template.
    """
    # First arg could be the menu template file name, or the parent page.
    # Also allow for both to be used.
    template_name = None
    parent_page = None
    parts = token.split_contents()[1:]
    for part in parts:
        part = Variable(part).resolve(context)
        if isinstance(part, unicode):
            template_name = part
        elif isinstance(part, Page):
            parent_page = part
    if template_name is None:
        try:
            template_name = context["menu_template_name"]
        except KeyError:
            error = "No template found for page_menu in: %s" % parts
            raise TemplateSyntaxError(error)
    context["menu_template_name"] = template_name
    if "menu_pages" not in context:
        try:
            user = context["request"].user
            slug = context["request"].path
        except KeyError:
            user = None
            slug = ""
        num_children = lambda id: lambda: len(context["menu_pages"][id])
        has_children = lambda id: lambda: num_children(id)() > 0
        rel = [m.__name__.lower() for m in Page.get_content_models()]
        published = Page.objects.published(for_user=user).select_related(*rel)
        # Store the current page being viewed in the context. Used
        # for comparisons in page.set_menu_helpers.
        if "page" not in context:
            try:
                context["_current_page"] = published.get(slug=slug)
            except Page.DoesNotExist:
                context["_current_page"] = None
        elif slug:
            context["_current_page"] = context["page"]
        # Some homepage related context flags. on_home is just a helper
        # indicated we're on the homepage. has_home indicates an actual
        # page object exists for the homepage, which can be used to
        # determine whether or not to show a hard-coded homepage link
        # in the page menu.
        home = home_slug()
        context["on_home"] = slug == home
        context["has_home"] = False
        # Maintain a dict of page IDs -> parent IDs for fast
        # lookup in setting page.is_current_or_ascendant in
        # page.set_menu_helpers.
        context["_parent_page_ids"] = {}
        pages = defaultdict(list)
        for page in published.order_by("_order"):
            page.set_helpers(context)
            context["_parent_page_ids"][page.id] = page.parent_id
            setattr(page, "num_children", num_children(page.id))
            setattr(page, "has_children", has_children(page.id))
            pages[page.parent_id].append(page)
            if page.slug == home:
                context["has_home"] = True
        context["menu_pages"] = pages
    # ``branch_level`` must be stored against each page so that the
    # calculation of it is correctly applied. This looks weird but if we do
    # the ``branch_level`` as a separate arg to the template tag with the
    # addition performed on it, the addition occurs each time the template
    # tag is called rather than once per level.
    context["branch_level"] = 0
    parent_page_id = None
    if parent_page is not None:
        context["branch_level"] = getattr(parent_page, "branch_level", 0) + 1
        parent_page_id = parent_page.id

    # Build the ``page_branch`` template variable, which is the list of
    # pages for the current parent. Here we also assign the attributes
    # to the page object that determines whether it belongs in the
    # current menu template being rendered.
    context["page_branch"] = context["menu_pages"].get(parent_page_id, [])
    context["page_branch_in_menu"] = False
    for page in context["page_branch"]:
        page.in_menu = page.in_menu_template(template_name)
        page.num_children_in_menu = 0
        if page.in_menu:
            context["page_branch_in_menu"] = True
        for child in context["menu_pages"].get(page.id, []):
            if child.in_menu_template(template_name):
                page.num_children_in_menu += 1
        page.has_children_in_menu = page.num_children_in_menu > 0
        page.branch_level = context["branch_level"]
        page.parent = parent_page

        # Prior to pages having the ``in_menus`` field, pages had two
        # boolean fields ``in_navigation`` and ``in_footer`` for
        # controlling menu inclusion. Attributes and variables
        # simulating these are maintained here for backwards
        # compatibility in templates, but will be removed eventually.
        page.in_navigation = page.in_menu
        page.in_footer = not (not page.in_menu and "footer" in template_name)
        if page.in_navigation:
            context["page_branch_in_navigation"] = True
        if page.in_footer:
            context["page_branch_in_footer"] = True

    t = get_template(template_name)
    return t.render(Context(context))
Example #14
0
def page_menu(context, token):
    """
    Return a list of child pages for the given parent, storing all
    pages in a dict in the context when first called using parents as keys
    for retrieval on subsequent recursive calls from the menu template.
    """
    # First arg could be the menu template file name, or the parent page.
    # Also allow for both to be used.
    template_name = None
    parent_page = None
    parts = token.split_contents()[1:]
    for part in parts:
        part = Variable(part).resolve(context)
        if isinstance(part, unicode):
            template_name = part
        elif isinstance(part, Page):
            parent_page = part
    if template_name is None:
        try:
            template_name = context["menu_template_name"]
        except KeyError:
            error = "No template found for page_menu in: %s" % parts
            raise TemplateSyntaxError(error)
    context["menu_template_name"] = template_name
    if "menu_pages" not in context:
        try:
            user = context["request"].user
            slug = context["request"].path
        except KeyError:
            user = None
            slug = ""
        num_children = lambda id: lambda: len(context["menu_pages"][id])
        has_children = lambda id: lambda: num_children(id)() > 0
        published = Page.objects.published(for_user=user)
        if slug == admin_url(Page, "changelist"):
            related = [m.__name__.lower() for m in Page.get_content_models()]
            published = published.select_related(*related)
        else:
            published = published.select_related(depth=2)
        # Store the current page being viewed in the context. Used
        # for comparisons in page.set_menu_helpers.
        if "page" not in context:
            try:
                context["_current_page"] = published.get(slug=slug)
            except Page.DoesNotExist:
                context["_current_page"] = None
        elif slug:
            context["_current_page"] = context["page"]
        # Maintain a dict of page IDs -> parent IDs for fast
        # lookup in setting page.is_current_or_ascendant in
        # page.set_menu_helpers.
        context["_parent_page_ids"] = {}
        pages = defaultdict(list)
        for page in published.order_by("_order"):
            context["_parent_page_ids"][page.id] = page.parent_id
            page.set_helpers(context)
            setattr(page, "num_children", num_children(page.id))
            setattr(page, "has_children", has_children(page.id))
            pages[page.parent_id].append(page)
        context["menu_pages"] = pages
        context["on_home"] = slug == reverse("home")
    # ``branch_level`` must be stored against each page so that the
    # calculation of it is correctly applied. This looks weird but if we do
    # the ``branch_level`` as a separate arg to the template tag with the
    # addition performed on it, the addition occurs each time the template
    # tag is called rather than once per level.
    context["branch_level"] = 0
    parent_page_id = None
    if parent_page is not None:
        context["branch_level"] = getattr(parent_page, "branch_level", 0) + 1
        parent_page_id = parent_page.id
    context["page_branch"] = context["menu_pages"].get(parent_page_id, [])
    context['page_branch_in_navigation'] = False
    context['page_branch_in_footer'] = False
    for page in context["page_branch"]:
        if page.in_navigation:
            context['page_branch_in_navigation'] = True
        if page.in_footer:
            context['page_branch_in_footer'] = True
        if (context.get('page_branch_in_navigation') and
            context.get('page_branch_in_footer')):
            break
    for i, page in enumerate(context["page_branch"]):
        context["page_branch"][i].branch_level = context["branch_level"]
        context["page_branch"][i].parent = parent_page
    t = get_template(template_name)
    return t.render(context)
Example #15
0
 def setUp(self):
     self.p = Page(title='test')
     self.p.save()
Example #16
0
class TestGetImageForPage(TestCase):
    def setUp(self):
        self.p = Page(title='test')
        self.p.save()

    def setUpDefaultImage(self):
        di = DefaultImage(file='default.jpg', type='BACKGROUND')
        di.save()

    def setUpPageImage(self):
        pi = PageImage(page=self.p, type='BACKGROUND', file='test.jpg')
        pi.save()

    def test_get_empty(self):
        self.assertEqual(
            '',
            get_image_for_page(self.p, 'BACKGROUND')
        )

    def test_get_default_image(self):
        self.setUpDefaultImage()

        self.assertEqual(
            '/static/media/default.jpg',
            get_image_for_page(self.p, 'BACKGROUND')
        )

    def test_get_specific_image(self):
        self.setUpDefaultImage()
        self.setUpPageImage()

        self.assertEqual(
            '/static/media/test.jpg',
            get_image_for_page(self.p, 'BACKGROUND')
        )

    def test_get_child_images(self):
        self.setUpDefaultImage()
        self.setUpPageImage()

        p1 = Page.objects.create(title='child1', parent=self.p)
        p2 = Page.objects.create(title='child2', parent=self.p)

        PageImage.objects.create(page=p2, type='BACKGROUND', file='child2.jpg')

        self.assertEqual(
            '/static/media/test.jpg',
            get_image_for_page(p1, 'BACKGROUND')
        )
        self.assertEqual(
            '/static/media/child2.jpg',
            get_image_for_page(p2, 'BACKGROUND')
        )

    def test_get_banner_image(self):
        DefaultImage.objects.create(type='BANNER', file='defaultbanner.jpg')

        self.assertEqual(
            '/static/media/defaultbanner.jpg',
            get_image_for_page(self.p, 'BANNER')
        )