def add(self, proxy): self.update() #TODO: check the role is at leat accessible to the current user userid = proxy.userid role = proxy.role target = proxy.target rid = self.normalize("r-%s-%s" % (userid, target)) if rid in self.container.objectIds(): return False request = self._new_request() request.id = rid request.role = role request.target = target request.target_path = proxy.target_path request.target_title = proxy.target_title request.userid = userid request.creatorid = proxy.creatorid request.rtype = proxy.rtype request.manage_setLocalRoles(userid, ["Owner"]) #Give Owner role also to people who can validate the request local_roles = self.context.get_local_roles() for target_userid, roles in local_roles: if target_userid == userid: continue request.manage_setLocalRoles(target_userid, list(roles)) addContentToContainer(self.container, request, checkConstraints=False) self.catalog.indexObject(self.container[rid]) event.notify(RequestAddedEvent(self.container[rid])) return True
def testAddContentToContainer_preserves_existing_id(self): from plone.dexterity.content import Item from plone.dexterity.content import Container container = Container() container._ordering = u'unordered' from zope.component import provideAdapter, provideUtility from zope.container.interfaces import INameChooser from zope.interface import Interface from plone.app.content.namechooser import NormalizingNameChooser from plone.folder.interfaces import IOrdering from plone.folder.unordered import UnorderedOrdering from plone.i18n.normalizer.interfaces import IURLNormalizer from plone.i18n.normalizer import URLNormalizer provideAdapter(NormalizingNameChooser, [Interface], INameChooser) provideUtility(URLNormalizer(), IURLNormalizer) provideAdapter(UnorderedOrdering, [Interface], IOrdering) # if the item has an id already, use it from plone.dexterity.utils import addContentToContainer item = Item() item.id = 'foo' item = addContentToContainer(container, item, checkConstraints=False) self.assertEqual(item.id, 'foo') # unless it's a duplicate item = Item() item.id = 'foo' item = addContentToContainer(container, item, checkConstraints=False) self.assertEqual(item.id, 'foo-1')
def setUpPloneSite(self, portal): # XXX: do not install (yet) PFG in Plone 5 if HAS_PFG and PLONE_VERSION < '5.0': self.applyProfile(portal, 'Products.PloneFormGen:default') # Install into Plone site using portal_setup self.applyProfile(portal, 'collective.cover:default') self.applyProfile(portal, 'collective.cover:testfixture') portal['my-image'].setImage(generate_jpeg(50, 50)) portal['my-image1'].setImage(generate_jpeg(50, 50)) portal['my-image2'].setImage(generate_jpeg(50, 50)) portal['my-file'].setFile(loadFile('lorem_ipsum.txt')) portal['my-file'].reindexObject() portal['my-news-item'].setImage(generate_jpeg(50, 50)) # Setup one a dexterity item from plone.dexterity.utils import createContent, addContentToContainer from plone.namedfile.file import NamedBlobImage as NamedImageFile context = createContent('testcontent', id='my-dexterity-item', title=u'My dexterity item') context.image = NamedImageFile(generate_jpeg(128, 128)) addContentToContainer(portal, context, checkConstraints=False) portal_workflow = portal.portal_workflow portal_workflow.setChainForPortalTypes(['Collection'], ['plone_workflow'],) # Prevent kss validation errors in Plone 4.2 portal_kss = getattr(portal, 'portal_kss', None) if portal_kss: portal_kss.getResource('++resource++plone.app.z3cform').setEnabled(False)
def testAddContentToContainer_preserves_existing_id(self): from plone.dexterity.content import Item from plone.dexterity.content import Container container = Container() container._ordering = u'unordered' # Allow anyone to access the contents information on the container. # This allows to check for existing content with the same id. container.manage_permission( 'Access contents information', ['Anonymous'], acquire=1) from zope.component import provideAdapter, provideUtility from zope.container.interfaces import INameChooser from zope.interface import Interface from plone.app.content.namechooser import NormalizingNameChooser from plone.folder.interfaces import IOrdering from plone.folder.unordered import UnorderedOrdering from plone.i18n.normalizer.interfaces import IURLNormalizer from plone.i18n.normalizer import URLNormalizer provideAdapter(NormalizingNameChooser, [Interface], INameChooser) provideUtility(URLNormalizer(), IURLNormalizer) provideAdapter(UnorderedOrdering, [Interface], IOrdering) # if the item has an id already, use it from plone.dexterity.utils import addContentToContainer item = Item() item.id = 'foo' item = addContentToContainer(container, item, checkConstraints=False) self.assertEqual(item.id, 'foo') # unless it's a duplicate item = Item() item.id = 'foo' item = addContentToContainer(container, item, checkConstraints=False) self.assertEqual(item.id, 'foo-1')
def render(self): context = self.context wt = self._wt data = open('%s/inscricoes.pickle' % PATH) data = pickle.load(data) i = 0 for item in data: reg,attendees = self.convertFromDict(item) if reg.id in context.objectIds(): continue regObj = addContentToContainer(context,reg) for attendee in attendees: attObj = addContentToContainer(regObj,attendee,checkConstraints=False) regObj.title = len(attendees) >1 and attObj.organization or attObj.fullname regObj.creation_date = item['created'] regObj.modification_date = item['modified'] regObj.workflow_history = self.fixWorkFlowHistory(item['workflow_history']) wt['registration_workflow'].updateRoleMappingsFor(regObj) regObj.reindexObject(['modified']) if item['review_state'] == 'inscrito': for attId in regObj.objectIds(): wt.doActionFor(regObj[attId],'confirm') i +=1 print i return 'Foo %d' % i
def getTopicWithLabel(topicObj, label): for obj in topicObj.objectValues(): if obj.Title() == label: return obj newtopic = createContent('collective.topictree.topic', title=label) addContentToContainer(topicObj, newtopic) topicObj = topicObj[newtopic.id] return topicObj
def create_sub_folder(container, id_, title): content = createContent('FlowSubFolder', title=title) IOwned(content).changeOwnership(IOwned(container).getOwner()) content.id = id_ content.schema = container.schema content.schema_digest = container.schema_digest addContentToContainer(container, content, checkConstraints=False) return container[id_]
def add(self, object): registration, attendee = object context = self.context regObject = addContentToContainer(context,registration) attObject = addContentToContainer(regObject,attendee,checkConstraints=False) regObject.title = attObject.title event = ObjectCreatedEvent(regObject) notify(event) self.immediate_view = "%s/%s" % (context.absolute_url(), regObject.id)
def handleRegister(self, action): print "handle registrer" data, errors = self.extractData() if errors: print "all errors views names", map(lambda err: err.widget.name, errors) print self.formErrorsMessage print "self.widgets.errors", self.widgets.errors self.status = self.formErrorsMessage return administrator = data['IAdministrator.administrator'] if api.user.get(username=administrator.username): raise ActionExecutionError(Invalid(u"Uživatelské jméno u správce producenta je již použito. Vyplňte jiné.")) # check administrator passwords if administrator.password_ctl != administrator.password: raise ActionExecutionError(Invalid(u"U správce producenta se neshodují zadaná hesla. Vyplňte hesla znovu.")) editorFields = ['fullname','email','phone','username','password','password_ctl'] editorValues = map(lambda key: data.get('IEditor.'+key,None), editorFields) if filter(lambda value: value, editorValues): if False in map(lambda value: bool(value), editorValues): raise ActionExecutionError(Invalid(u"Některé položky u editora nejsou vyplněny. Buď vyplňte editorovi všechny položky, nebo je všechny smažte.")) editorData = dict(zip(editorFields, editorValues)) if editorData['password'] != editorData['password_ctl']: raise ActionExecutionError(Invalid(u"U editora se neshodují zadaná hesla. Vyplňte hesla znovu.")) if api.user.get(username=editorData['username']): raise ActionExecutionError(Invalid(u"Uživatelské jméno u editora je již obsazené. Vyplňte jiné.")) producentsFolder = self.getProducentsFolder() # hack for title and description data['title'] = data.get('IBasic.title','') data['description'] = data.get('IBasic.description','') producent = createContentInContainer(producentsFolder, "edeposit.user.producent", **data) if filter(lambda value: value, editorValues): editorsFolder = producent['producent-editors'] editorData['title'] = editorData['fullname'] editor = createContentInContainer(editorsFolder, "edeposit.user.producenteditor", **editorData) administratorsFolder = producent['producent-administrators'] administrator.title = getattr(administrator,'fullname',None) addContentToContainer(administratorsFolder, administrator, False) if producent is not None: wft = api.portal.get_tool('portal_workflow') wft.doActionFor(producent,'submit') # mark only as finished if we get the new object self._finishedAdd = True IStatusMessage(self.request).addStatusMessage(_(u"Item created"), "info") url = "%s/%s" % (api.portal.getSite().absolute_url(), 'register-with-producent-successed') self.request.response.redirect(url)
def add(self, object): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) addContentToContainer(container, object) parentfti = getUtility(IDexterityFTI, name=container.portal_type) if parentfti.immediate_view: self.immediate_view = '/'.join( [container.absolute_url(), fti.immediate_view]) else: self.immediate_view = '/'.join([container.absolute_url()])
def createNewDay(self, new_date, content): id = new_date.strftime('%a-%b.-%d-%Y') id = queryUtility(IURLNormalizer).normalize(id) #Need to copy in all of the conects of the original day nday = createContent( 'collective.dexterity.appointments.appointmentday', appointment_date=new_date) new_day = addContentToContainer(self.parent, nday) new_day.manage_pasteObjects(content) #Yes I know this is gross, but under time restrictions. for time_slot in new_day.contentItems(): time_slot[1].start = time_slot[1].start + ( new_day.appointment_date - time_slot[1].start.date()) time_slot[1].end = time_slot[1].end + (new_day.appointment_date - time_slot[1].end.date()) new_day.reindexObject() import pdb pdb.set_trace() return new_day
def createNewTimeSlot(self, start, end, max_capacity, allow_waiting, name): id = (start.strftime('%I-%M-%p') + '_' + end.strftime('%I-%M-%p')).lower() try: time_slot = createContent('collective.dexterity.appointments.timeslot', start=start, end=end, name=name, max_capacity=max_capacity, allow_waitlist=allow_waiting) addContentToContainer(self.parent,time_slot) except BadRequest: self.success = False self.errors.append("An object already exists with id: %s" % id) return None new_time_slot = "lol" return new_time_slot
def create_subtask(task, data): subtask = createContent('opengever.task.task', id=data['title'], **data) notify(ObjectCreatedEvent(subtask)) subtask = addContentToContainer(task, subtask, checkConstraints=True) for schemata in iterSchemata(subtask): super_repr = schemata(task) repr = schemata(subtask) for name, field in schema.getFieldsInOrder(schemata): if name in data: value = data[name] else: value = getattr(super_repr, name, None) setattr(repr, name, value) activity = TaskAddedActivity(subtask, task.REQUEST, task) activity.record() notify(ObjectModifiedEvent(subtask)) return subtask
def create_testobject(parent, ptype, **kwargs): createContent(ptype) obj = createContent(ptype, **kwargs) notify(ObjectCreatedEvent(obj)) obj = addContentToContainer(parent, obj, checkConstraints=False) notify(ObjectAddedEvent(obj)) return obj
def add(self, object): """Add the object to the container skipping constraints and redirect to the container. """ container = aq_inner(self.context) data, errors = self.extractData() if errors: return # Validate Captcha anon = api.user.is_anonymous() good_to_go = False if 'captcha' not in data: data['captcha'] = u"" captcha = validator.CaptchaValidator(self.context, self.request, None, IClaim['captcha'], None) if captcha.validate(data['captcha']): good_to_go = True else: good_to_go = True if good_to_go: obj = addContentToContainer( container, object, checkConstraints=False) self.immediate_view = '{0}/{1}'.format( container.absolute_url(), obj.id)
def add_invitation_to_context(context, invitation): ''' adds an invitation to a invitation folder in the provided context if no invitation folder is found, it tries to creates one default ''' import pdb pdb.set_trace() portal = getSite() catalog = getToolByName(portal, "portal_catalog") query = {} query['object_provides'] = IInvitationFolder.__identifier__ query['path'] = dict(query='/'.join(context.getPhysicalPath())) invitationfolders = catalog(query) if not invitationfolders: invitationfolder = createContent( portal_type='hejasverige.invitationfolder', title='invitations', description='folder for invitations') try: folder = addContentToContainer(container=context, object=invitationfolder, checkConstraints=True) folder.reindexObject() except Exception, ex: err = 'Unable to create invitaiton folder in', str( folder), 'due to', str(ex) logger.exception(err) return None
def add(obj, container): # add container = aq_inner(container) obj = addContentToContainer(container, obj) if obj: notify(ObjectAddedEvent(obj)) return obj
def add(self, object): training = object # We look for the right track to add the training context = self.track_object(training) trainingObj = addContentToContainer(context, training) self.immediate_view = "%s/%s" % (context.absolute_url(), trainingObj.id)
def create_object(self): """Creates an instance of our dexterity content type. Performs the following actions in order: - Create the instance - Set field values and default values - Fire a created event - Add content to its container """ self.insert_field_default_values() content = self._create_content() # Acquisition wrap content temporarily to make sure schema # interfaces can be adapted to `content` content = content.__of__(self.container) self.set_field_values(content) self.set_missing_values_for_empty_fields(content) self.set_properties(content) # Remove temporary acquisition wrapper content = aq_base(content) notify(ObjectCreatedEvent(content)) obj = addContentToContainer( self.container, content, checkConstraints=self.checkConstraints) return obj
def add(self, object): """Add the object to the container skipping constraints and redirect to the container. """ container = aq_inner(self.context) data, errors = self.extractData() if errors: return # Validate Captcha anon = api.user.is_anonymous() good_to_go = False if 'captcha' not in data: data['captcha'] = u"" captcha = validator.CaptchaValidator(self.context, self.request, None, IClaim['captcha'], None) if captcha.validate(data['captcha']): good_to_go = True else: good_to_go = True if good_to_go: obj = addContentToContainer(container, object, checkConstraints=False) self.immediate_view = '{0}/{1}'.format(container.absolute_url(), obj.id)
def create_main_task(self, templatefolder, selected_templates): highest_deadline = max( [template.deadline for template in selected_templates]) data = dict( title=templatefolder.title, issuer=self.replace_interactive_user('current_user'), responsible=self.replace_interactive_user('current_user'), responsible_client=get_current_org_unit().id(), task_type='direct-execution', deadline=date.today() + timedelta(highest_deadline + MAIN_TASK_DEADLINE_DELTA), ) main_task = createContent('opengever.task.task', **data) notify(ObjectCreatedEvent(main_task)) main_task = addContentToContainer( self.context, main_task, checkConstraints=True) self.mark_as_generated_from_tasktemplate(main_task) # set the main_task in to the in progress state api.content.transition(obj=main_task, transition='task-transition-open-in-progress') return main_task
def create_task(parent, **kwargs): createContent('opengever.task.task') task = createContent('opengever.task.task', **kwargs) notify(ObjectCreatedEvent(task)) task = addContentToContainer(parent, task, checkConstraints=False) notify(ObjectAddedEvent(task)) return task
def add(self, object): """Add the object to the container skipping constraints and redirect to the container. """ container = aq_inner(self.context) obj = addContentToContainer(container, object, checkConstraints=False) self.immediate_view = '{0}/{1}'.format(container.absolute_url(), obj.id)
def create_main_task(self, templatefolder, selected_templates): highest_deadline = max( [template.deadline for template in selected_templates]) deadline_timedelta = api.portal.get_registry_record( 'deadline_timedelta', interface=ITaskSettings) data = dict( title=templatefolder.title, issuer=self.replace_interactive_user('current_user'), responsible=self.replace_interactive_user('current_user'), responsible_client=get_current_org_unit().id(), task_type='direct-execution', deadline=date.today() + timedelta(highest_deadline + deadline_timedelta), ) main_task = createContent('opengever.task.task', **data) notify(ObjectCreatedEvent(main_task)) main_task = addContentToContainer(self.context, main_task, checkConstraints=True) self.mark_as_generated_from_tasktemplate(main_task) # set the main_task in to the in progress state api.content.transition(obj=main_task, transition='task-transition-open-in-progress') return main_task
def add_object(task, container, task_id): task_record = utils.get_task(task_id) obj = task_record["obj"] try: zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) new_obj = dexterity_utils.addContentToContainer(container, obj) uuid = IUUID(new_obj) record_task_result.apply_async([task_id, constants.SUCCESS], dict(obj=None, obj_uid=uuid)) transaction.commit() except ConflictError: retries = task.request.retries + 1 max_retries = task.max_retries if max_retries is not None and retries > max_retries: tb = traceback.format_exc() record_task_result.apply_async( [task_id, constants.ERROR], dict(obj=None, tb=tb), without_transaction=True, ) raise except Exception as e: exc = str(e) tb = traceback.format_exc() record_task_result.apply_async( [task_id, constants.ERROR], dict(obj=None, message=exc, tb=tb), without_transaction=True, ) raise
def createContentInContainer(container, portal_type, checkConstraints=True, **kw): alsoProvides(container.REQUEST, IDuringContentCreation) # Also pass container to createContent so it is available for # determining default values content = createContentWithDefaults(portal_type, container, **kw) result = addContentToContainer( container, content, checkConstraints=checkConstraints) noLongerProvides(container.REQUEST, IDuringContentCreation) return result
def __call__(self): if self.request.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if not filedata: return filename = safe_unicode(filedata.filename.decode("utf8")) content_type = guess_type(filename)[0] or "" language = splitext(filename)[0][-2:] obj_id = hashlib.md5(splitext(filename)[0][:-3]).hexdigest() # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() try: transaction.begin() file_ = NamedBlobFile( data=filedata, filename=filename, contentType=content_type, ) if obj_id in self.context.objectIds(): obj = self.context[obj_id] setattr(obj, language + '_file', file_) else: obj = createContent( 'unep.file', **({language + '_file': file_}) ) obj.id = obj_id obj = addContentToContainer(self.context, obj) obj.reindexObject() transaction.commit() finally: upload_lock.release() if language == 'en': language = 'English' elif language == 'es': language = 'Spanish' elif language == 'fr': language = 'French' self.request.RESPONSE.setHeader('content-type', 'application/json') return json.dumps({ 'uid': obj.UID(), 'title': obj.title, 'language': language, 'url': obj.absolute_url(), })
def __call__(self): if self.request.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if not filedata: return filename = safe_unicode(filedata.filename.decode("utf8")) content_type = guess_type(filename)[0] or "" language = splitext(filename)[0][-2:] obj_id = hashlib.md5(splitext(filename)[0][:-3]).hexdigest() # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() try: transaction.begin() file_ = NamedBlobFile( data=filedata, filename=filename, contentType=content_type, ) if obj_id in self.context.objectIds(): obj = self.context[obj_id] setattr(obj, language + '_file', file_) else: obj = createContent('unep.file', **({ language + '_file': file_ })) obj.id = obj_id obj = addContentToContainer(self.context, obj) obj.reindexObject() transaction.commit() finally: upload_lock.release() if language == 'en': language = 'English' elif language == 'es': language = 'Spanish' elif language == 'fr': language = 'French' self.request.RESPONSE.setHeader('content-type', 'application/json') return json.dumps({ 'uid': obj.UID(), 'title': obj.title, 'language': language, 'url': obj.absolute_url(), })
def add(self, obj): # not checking the contrains means two things # * impossible content types could theoretically added # * anonymous users can post events self.content = addContentToContainer( aq_inner(self.context), obj, checkConstraints=False ) self.apply_coordinates(self.content) apply_token(self.content)
def add(self, obj): # not checking the contrains means two things # * impossible content types could theoretically added # * anonymous users can post events self.content = addContentToContainer(aq_inner(self.context), obj, checkConstraints=False) self.apply_coordinates(self.content) apply_token(self.content)
def create(self, container, data): title = data['title'] if not isinstance(title, unicode): title = title.decode('utf-8') obj = createContent(data['portal_type'], id=title, title=title) notify(ObjectCreatedEvent(obj)) obj = addContentToContainer(container, obj, checkConstraints=True) return obj
def add(self, object): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) new_object = addContentToContainer(container, object) if fti.immediate_view: self.immediate_view = "%s/%s/%s" % (container.absolute_url(), new_object.id, fti.immediate_view,) else: self.immediate_view = "%s/%s" % (container.absolute_url(), new_object.id)
def create_in(self, container): obj = createContent(self.portal_type, title=self.title) notify(ObjectCreatedEvent(obj)) # insert data from collectors collectors = getAdapters((obj.__of__(container),), IDataCollector) for name, collector in collectors: collector.insert(self.data[name]) obj = addContentToContainer(container, obj, checkConstraints=True) return obj
def create_in(self, container): obj = createContent(self.portal_type, title=self.title) notify(ObjectCreatedEvent(obj)) # insert data from collectors collectors = getAdapters((obj.__of__(container), ), IDataCollector) for name, collector in collectors: collector.insert(self.data[name]) obj = addContentToContainer(container, obj, checkConstraints=True) return obj
def add(self, submission): try: # noinspection PyProtectedMember attachments = submission._v_attachments delattr(submission, '_v_attachments') except AttributeError: attachments = [] folder = self.context for folder in parents(folder, IFlowFolder): # Traverse from IFlowSubFolders to IFlowFolder break container = get_submission_container( folder, self.context, submission.__of__(self.context), ) submission = addContentToContainer( container, submission, checkConstraints=False, ) for attachment in attachments: notify(ObjectCreatedEvent(attachment)) addContentToContainer( submission, attachment, checkConstraints=False, ) # fire submission and attachment transitions fire_default_transitions( submission, self.submission_transition, self.attachment_transition, ) content = submission.__of__(self.context) submission.title = get_submission_title(folder, content) submission.reindexObject(idxs=['title']) self.content = content
def add_relation(self, id, member_type='supporter'): relobj = createContent(portal_type='hejasverige.relation', foreign_id=id, ) try: item = addContentToContainer(container=self.__parent__, object=relobj, checkConstraints=False) except Exception, ex: err = 'Unable to add relation with id', id, 'to', str(self.__parent__), 'due to', str(ex) print err #log(err) return None
def create_obj(self,source_obj=None, target_parent=None, transition=True): from plone import api from plone.dexterity.content import Container from plone.dexterity.content import Item from plone.dexterity.utils import addContentToContainer target_obj = None # is the source a Dexterity object if isinstance(source_obj,Container) or isinstance(source_obj, Item): # Dexterity source_data = DexterityData(source_obj).items() expires = source_data.pop('expires') \ if source_data.has_key('expires') else None mf = MigrationFactory() context = mf.getMigrationContext(source_data) target_obj = addContentToContainer(target_parent,context) if expires: target_obj.setExpirationDate(expires) else: # Archetype # api.copy doesn't return the target_obj so we use container # methods instead source_id = source_obj.getId() ids = target_parent.manage_pasteObjects(source_obj.manage_copyObjects(source_id)) if ids[0]['new_id'] == ids[0]['id']: target_obj = target_parent[source_id] else: from zope.container.interfaces import INameChooser chooser = INameChooser(target_parent) new_id = chooser.chooseName(source_id, source_obj) target_parent.manage_renameObject(ids[0]['new_id'], new_id) target_obj = target_parent[new_id] if (target_obj != None) & transition: # state = api.content.get_state(source_obj) # if state == u'internal': # api.content.transition(target_obj, transition=u'publish_internaly') # elif state == u'external': # api.content.transition(target_obj, transition=u'submit') # api.content.transition(target_obj, transition=u'publish_externally') from Products.CMFCore.utils import getToolByName workflowTool = getToolByName(api.portal.get(),'portal_workflow') print "/".join(source_obj.getPhysicalPath()) status = workflowTool.getStatusOf('intranet_workflow',source_obj) if status: state = status['review_state'] if state == u'internal': workflowTool.doActionFor(target_obj,'publish_internally') elif state == u'external': workflowTool.doActionFor(target_obj,'submit') workflowTool.doActionFor(target_obj,'publish_externally') return target_obj
def add(self, object): fti = getUtility(IDexterityFTI, name=self.portal_type) new_object = addContentToContainer(self.container, object) if fti.immediate_view: self.immediate_view = "/".join( [self.container.absolute_url(), new_object.id, fti.immediate_view] ) else: self.immediate_view = "/".join( [self.container.absolute_url(), new_object.id] )
def createNewTimeSlot(self, start, end, max_capacity, allow_waiting, name): id = (start.strftime('%I-%M-%p') + '_' + end.strftime('%I-%M-%p')).lower() try: time_slot = createContent( 'collective.dexterity.appointments.timeslot', start=start, end=end, name=name, max_capacity=max_capacity, allow_waitlist=allow_waiting) addContentToContainer(self.parent, time_slot) except BadRequest: self.success = False self.errors.append("An object already exists with id: %s" % id) return None new_time_slot = "lol" return new_time_slot
def add_person(self, container, person): personobject = createContent(portal_type='hejasverige.person', first_name=person.get('first_name', None), last_name=person.get('last_name', None), personal_id=person.get('personal_id', None) ) #import pdb; pdb.set_trace() try: item = addContentToContainer(container=container, object=personobject, checkConstraints=False) except Exception, ex: err = 'Unable to add person with id', id, 'to', str(container), 'due to', str(ex) logger.exception(err) return None
def _make_measure(self, data): kw = {} # field values for new measure # use defaults for rounding, display_precision, infer if percentage use_pct = self.data_implies_percentage(data) kw.update({ 'rounding': '', 'display_precision': 1 if use_pct else 0, 'express_as_percentage': use_pct, }) if self.context.source_type == MULTI_FORM_TYPE: calc = data.get('IMeasureWizardMRCriteria') else: calc = data.get('IMeasureWizardFlexFields') # flex form kw.update(calc) # mr: numerator/denominator types; flex: fields measure = createContent(MEASURE_DEFINITION_TYPE, **kw) if kw.get('express_as_percentage', False): measure.multiplier = 100.0 measure.value_type = 'percentage' else: measure.value_type = 'count' addContentToContainer(self.context, measure) # will auto-choose id return measure.__of__(self.context)
def add(self, object): fti = getUtility(IDexterityFTI, name=self.portal_type) new_object = addContentToContainer(self.container, object) if fti.immediate_view: self.immediate_view = "/".join([ self.container.absolute_url(), new_object.id, fti.immediate_view ]) else: self.immediate_view = "/".join( [self.container.absolute_url(), new_object.id])
def add(self,object): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) new_object = addContentToContainer(container, object) self.new_object = new_object if fti.immediate_view: self.immediate_view = "%s/%s/%s" % (container.absolute_url(), new_object.id, fti.immediate_view,) else: self.immediate_view = "%s/%s" % (container.absolute_url(), new_object.id) for author in filter(lambda author: author.fullname, self.authors): author.title = author.fullname addContentToContainer(new_object, author, True) if self.originalFile: value = self.originalFile newOriginalFile = createContentInContainer(new_object,'edeposit.content.originalfile',**value) wft = api.portal.get_tool('portal_workflow') if newOriginalFile.file: wft.doActionFor(newOriginalFile, (newOriginalFile.isbn and 'submitDeclarationToISBNValidation') or ('submitDeclarationToAntivirus'), comment='handled automatically')
def add(self, obj): """Create outgoing mail in outgoing-mail folder.""" fti = getUtility(IDexterityFTI, name=self.portal_type) container = api.portal.get()['outgoing-mail'] new_object = addContentToContainer(container, obj) if fti.immediate_view: self.immediate_view = "/".join( [container.absolute_url(), new_object.id, fti.immediate_view] ) else: self.immediate_view = "/".join( [container.absolute_url(), new_object.id] )
def add(self, object): fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) new_object = addContentToContainer(container, object) # import pdb # pdb.set_trace() notify(PreviewableFileCreatedEvent(new_object)) if fti.immediate_view: self.immediate_view = "/".join( [container.absolute_url(), new_object.id, fti.immediate_view]) else: self.immediate_view = "/".join( [container.absolute_url(), new_object.id])
def add(self, object): """ """ fti = getUtility(IDexterityFTI, name=self.portal_type) container = aq_inner(self.context) new_object = addContentToContainer(container, object, checkConstraints=False) if fti.immediate_view: self.immediate_view = "/".join( [container.absolute_url(), new_object.id, fti.immediate_view]) else: self.immediate_view = "/".join( [container.absolute_url(), new_object.id])
def add_person(self, container, person): personobject = createContent(portal_type='hejasverige.person', first_name=person.get('first_name', None), last_name=person.get('last_name', None), personal_id=person.get( 'personal_id', None)) #import pdb; pdb.set_trace() try: item = addContentToContainer(container=container, object=personobject, checkConstraints=False) except Exception, ex: err = 'Unable to add person with id', id, 'to', str( container), 'due to', str(ex) logger.exception(err) return None
def do_POST(self): if not self.has_permission('Euphorie: Manage country'): raise Unauthorized() sector = createContent('euphorie.sector') # Assign a temporary id. Without this security caching logic breaks due to use of # getPhysicalPath() as cache id. This calls getId() to get the id, # which uses __name__ if no id is set, but __name__ is a computer attribute which # calls getId. BOOM! sector.id = str(id(sector)) try: self.update_object(self.attributes, ISector, sector.__of__(self.context)) except ValueError as e: return {'type': 'error', 'message': str(e)} del sector.id sector = addContentToContainer(self.context.country, sector, False) view = SectorView(sector, self.request) return view.do_GET()
def add_invitation(self, container, invitation): invitationobject = createContent( portal_type='hejasverige.invitation', sender_id=invitation.get('sender_id', None), first_name=invitation.get('first_name', None), last_name=invitation.get('last_name', None), personal_id=invitation.get('personal_id', None), recipient_email=invitation.get('recipient_email', None), invitation_expires=invitation.get('invitation_expires', None)) try: item = addContentToContainer(container=container, object=invitationobject, checkConstraints=False) item.reindexObject() except Exception, ex: err = 'Unable to add invitation with id', id, 'to', str( container), 'due to', str(ex) logger.exception(err) return None