Thursday, June 9, 2011

Programmatically Adding Image Content in Generic Setup

Have you been sitting around for the last hour thinking "man, it would sure be great if I could add Images to my site on install but I just can't find a code example"? I know I was. Consider it documented!

There will be a slideshow in the Plone Conference 2011 website (it's coming soon I swear!) that we wanted to work on install since it was 1. on the front page and 2. a PITA to set up every time. The code below gives "a" way to do this, although it could be taken to a much more abstracted level (what couldn't?!?).

This assumes that there is a folder called images in your generic setup profile folder, which is likely to be in ... > profiles > default > images. The nice thing is that it doesn't rely on the magical, mystical .content jiggery. I won't rehash the code comments, but if you are using the slideshow product then maybe this cantation is for you!

import StringIO
import transaction
def setupVarious(context):
if context.readDataFile('ploneconf2011.theme_default.txt') is None:
return
# set the default front page property of layout to be a new view
site = context.getSite()
front = site.get('front-page')
if front:
front.layout = 'home_page_view'
# set the initial images
slide = site.get('slideshow-folder')
if slide:
# only add if this is a first time setup
if not slide.getChildNodes():
# XXX: this would be fun if it was reading a metadata file instead :)
# dreams for another day I guess...
addMe = [
("ss-sprint.jpg", "Contribute Back", "Sprint | November 7-8"),
("ss-conf.jpg", "Catch Up", "Conference | November 3-6"),
("ss-training.jpg", "Get Learned", "Training | November 1-2"),
]
for (location, title, description) in addMe:
imageId = location.split(".")[0]
imageFile = context.openDataFile(location, 'images')
if imageFile:
transaction.begin() # in case this list is big
slide.invokeFactory(id=imageId, type_name='Image')
newImage = slide.get(imageId)
newImage.setImage(imageFile.read())
imageFile.close()
newImage.setTitle(title)
newImage.setDescription(description)
# required for title/desc to be in catalog
newImage.reindexObject()
transaction.commit()
view raw fart.py hosted with ❤ by GitHub

2 comments:

  1. sweet!! that is amazeballs. no more "do shit" though? :D

    how does updating the slideshow work after this point? do you just come in and edit the script, and then reimport the thingy, or can it be done through the web after it's been installed?

    ReplyDelete
  2. yeah - sorry - we need the front page to be "the government is paying my way" acceptable :(

    Edit TTW after initial setup so you can update with new pictures whenever you WANT! I just wanted to put something in there - that's def not a final cut let's say :)

    ReplyDelete