Stephen Moran
Stephen Moran

Reputation: 306

Plone 4: how to get the context for a sub-folder with a hyphen in the shortname

I am writing a python script to import content from another CMS into Plone 4.1. For a number of reasons I am running it like so: bin/instance run path/to/myscript

The question I have is how to get the correct context for a folder with a hyphen in the ID/shortname. For example from the root of a plone site called mysite, I can work with a folder called "sub-folder" like so:

from Products.CMFCore.utils import getToolByName
urltool = getToolByName(app.mysite, "portal_url")
portal  = urltool.getPortalObject()
folder = getattr(portal, 'sub-folder')

But if I then want to create a folder or page within that sub-folder, the following throws an error: "AttributeError: sub"

urltool = getToolByName(app.mysite.sub-folder, "portal_url")
portal  = urltool.getPortalObject()

And performing the same on the News folder, (which has no hyphen) produces no error:

urltool = getToolByName(app.mysite.news, "portal_url")
portal  = urltool.getPortalObject()

Simply trying portal.sub-folder throws the same Error.

So what would be the python code to get the proper context of "http://localhost:8080/mysite/sub-folder" so that I can then successfully call the invokeFactory method and create a folder or page within mysite/sub-folder?

What if I needed to find the context of "http://localhost:8080/mysite/sub-folder/2nd-level" ?

The online documentation I have found seems to only account for folders named dog or news, which have no hyphen in the ID/Shortname. However, if you create these items by hand in Plone, the shortnames obviously have hyphens, and so there must be a way to get the correct folder context.

Upvotes: 2

Views: 1119

Answers (2)

jeorgen
jeorgen

Reputation: 656

You already do:

folder = getattr(portal, 'sub-folder')

So you have the folder with a hyphen right there, referenced in the "folder" variable.

You can use the folder variable to call invokeFactory and you're done. It knows where it is in Plone.

You do not need to get hold of the portal_url tool to run invokeFactory. But if you want it, instead of as you write:

getToolByName(app.mysite.sub-folder, "portal_url")

You could do:

getToolByName(folder, "portal_url")

However presently (and probably forever) you do not even need to do that, since the portal_url tool for your sub folder is the same one as for the entire site, so you could just write:

urltool = getToolByName(app.mysite, "portal_url")

Upvotes: 0

Giacomo Spettoli
Giacomo Spettoli

Reputation: 4496

That's because if you use:

app.mysite.sub-folder

python thinks that you're trying to do a difference between app.mysite.sub and folder. Instead you have to use this syntax:

secondlevel = mysite['sub-folder']['2nd-level']

or

secondlevel = mysite.restrictedTraverse('/mysite/sub-folder/2nd-level')

Upvotes: 4

Related Questions