How to use Page method in storybook-root

Best JavaScript code snippet using storybook-root

reportbuilder.py

Source:reportbuilder.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2##Copyright (C) [2005] [Jürgen Hamel, D-32584 Löhne]3##This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as4##published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.5##This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied6##warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License7##for more details.8##You should have received a copy of the GNU General Public License along with this program; if not, write to the9##Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 10import sys11import os12import os.path13import types14import pygtk15pygtk.require('2.0')16import gtk17import gtk.glade18import gobject19import string20import logging21import cPickle22#import cuon.OpenOffice.letter23# localisation24import locale, gettext25locale.setlocale (locale.LC_NUMERIC, '')26import threading27import datetime as DateTime28import drawingReport29import cuon.Misc.cuon_dialog30from modifyEntry import modifyEntryWindow31class reportbuilderwindow(modifyEntryWindow):32 33 def __init__(self, dicFilename = None):34 35 modifyEntryWindow.__init__(self)36 self.dicPage = {}37 self.dicText = {}38 # self.setLogLevel(self.INFO)39 40 self.dicText['class'] = 'Label'41 self.dicText['text'] = 'NoTitle'42 self.dicText['x1'] = 043 self.dicText['x1'] = 044 self.dicText['y1'] = 045 self.dicText['x2'] = 046 self.dicText['y2'] = 047 self.dicText['font'] = 'courier'48 self.dicText['fontsize'] = 1249 self.dicText['kursiv'] = 'no'50 self.dicText['bold'] = 'no'51 self.dicText['underline'] = 'no'52 self.dicText['subscript'] = 'no'53 self.dicText['fontjustification'] = 'left'54 self.dicText['yOffSet'] = 2055 self.dicText['Papersize'] = self.pagesizes['A4']56 self.dicText['Papersize_Width'], self.dicText['Papersize_Height'] = self.dicText['Papersize']57 58 self.dicText['Orientation'] = 'Portrait' # 'Landscape' # 'Portrait'59 60 self.dicPage['ReportFootAppendToGroup'] = 0 61 self.dicPage['PageFootAppendToGroup'] = 0 62 63 self.dicText['TopMargin'] = 3064 self.activeRegion = 165 self.activeGroup = 066 self.activeDA = None67 self.drawReportHeader = {}68 self.drawPageHeader = {}69 self.drawGroup = {}70 self.drawPageFooter = {}71 self.drawReportFooter = {}72 self.reportHeaderDA = None73 self.PageHeaderDA = None74 self.reportGroupsDA = []75 self.PageFooterDA = None76 self.reportFooterDA = None77 78 79 daR = self.getWidget('daReportHeader')80 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)81 82 daR = self.getWidget('daPageHeader')83 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)84 85 daR = self.getWidget('daGroups')86 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)87 88 daR = self.getWidget('daPageFooter')89 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)90 91 daR = self.getWidget('daReportFooter')92 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)93 94 95 96 #self.loadGlade('reportbuilder.xml')97 98 self.win1 = self.getWidget('reportbuildermainwindow')99 self.win1.show()100 101 #self.setStatusBar()102 103 print 'dicFilename at reportbuilder', dicFilename104 if dicFilename:105 self.dicCurrentFilename = dicFilename106 self.readReportDocument(dicFilename)107 else:108 self.dicCurrentFilename = {'TYPE':'FILE','NAME':'./new.txt'}109 110 111 # menu File112 def on_save_activate(self, event):113 print 'save clicked'114 self.saveFile()115 116 117 #Events118 119 # Report Header120 121 122 123 def on_daReportHeader_button_press_event(self, oWidget, data):124 125 print 'mouse button = ', oWidget , data, data.x, data.y126 self.activateClick("rRHactive", "clicked")127 if data.button == 3:128 liEntries = self.reportHeaderDA.getEntryAtPosition(data.x, data.y)129 if liEntries:130 self.chooseFromEntries(liEntries)131 132 133 134 def on_daReportHeader_key_press_event(self, oWidget, data ):135 print 'key = ', oWidget, data136 137 138 139 # Page Header140 141 142 143 def on_daPageHeader_button_press_event(self, oWidget, data):144 145 print 'mouse button = ', oWidget , data, data.x, data.y146 self.activateClick("rPHactive", "clicked")147 if data.button == 3:148 liEntries = self.PageHeaderDA.getEntryAtPosition(data.x, data.y)149 150 if liEntries:151 self.chooseFromEntries(liEntries)152 153 def on_daPageHeader_key_press_event(self, oWidget, data ):154 print 'key = ', oWidget, data155 156 # Report Groups157 158 159 160 def on_daGroups_button_press_event(self, oWidget, data):161 162 print 'mouse button = ', oWidget , data, data.x, data.y163 self.activateClick("rGactive", "clicked")164 if data.button == 3:165 liEntries = self.reportGroupsDA[0].getEntryAtPosition(data.x, data.y)166 167 if liEntries:168 self.chooseFromEntries(liEntries)169 170 171 def on_daGroups_key_press_event(self, oWidget, data ):172 print 'key = ', oWidget, data173 174 # Page Footer175 176 177 178 def on_daPageFooter_button_press_event(self, oWidget, data):179 180 print 'mouse button = ', oWidget , data, data.x, data.y181 self.activateClick("rPFactive", "clicked")182 if data.button == 3:183 liEntries = self.PageFooterDA.getEntryAtPosition(data.x, data.y)184 185 if liEntries:186 self.chooseFromEntries(liEntries)187 188 189 190 191 def on_daPageFooter_key_press_event(self, oWidget, data ):192 print 'key = ', oWidget, data193 194 # Report Footer195 196 197 198 def on_daReportFooter_button_press_event(self, oWidget, data):199 200 print 'mouse button = ', oWidget , data, data.x, data.y201 self.activateClick("rRFactive", "clicked")202 if data.button == 3:203 liEntries = self.reportFooterDA.getEntryAtPosition(data.x, data.y)204 self.chooseFromEntries(self, liEntries) 205 206 207 208 209 210 211 def on_daReportFooter_key_press_event(self, oWidget, data ):212 print 'key = ', oWidget, data213 214 215 216 217 # toggle report part218 219 def on_rAll_toggled(self, event):220 print 'radiobutton toggled'221 liButtons = ['rRHactive', 'rPHactive','rGactive','rPFactive','rRFactive']222 for l in range (len(liButtons)):223 rAll = self.getWidget(liButtons[l])224 if rAll.get_active():225 self.activeRegion = l+1226 print 'active = ', self.activeRegion227 228 # functions229 def chooseFromEntries(self, liEntries): 230 #print liEntries, len(liEntries)231 if len(liEntries)> 1:232 sText = 'Choose: \n'233 for l in range(0, len(liEntries)):234 sText += `l` + " " + liEntries[l]['name'] + "\n"235 236 cd = cuon.Misc.cuon_dialog.cuon_dialog()237 ok, res = cd.inputLine( 'choose', sText)238 print 'ok = ', ok, 'Res = ', res239 if ok and res: 240 try:241 self.modifyEntry(liEntries[int(res)])242 except:243 pass244 245 246 247 else:248 self.modifyEntry(liEntries[0]) 249 def modifyEntry(self, dicEntry):250 self.ModifyEntryShow(dicEntry)251 252 def on_bRefresh_clicked(self, event):253 print 'bRefresh clicked'254 self.activeDA.area_expose_cb(None, event)255 256 257 def on_tbSave_clicked(self, event):258 self.activateClick('save')259 #self.saveFile()260 261 def replaceEntry(self, dicEntry):262 263 print 'active Region = ', self.activeRegion264 self.activeDA = None265 if self.activeRegion == 1:266 self.activeDA = self.reportHeaderDA267 elif self.activeRegion == 2:268 self.activeDA= self.PageHeaderDA269 elif self.activeRegion == 3:270 self.activeDA = self.reportGroupsDA[self.activeGroup]271 elif self.activeRegion == 4:272 self.activeDA = self.PageFooterDA273 elif self.activeRegion == 5:274 self.activeDA = self.reportFooterDA 275 276 self.activeDA.replaceEntryByName(dicEntry)277 def save_file(self, dicFilename, data):278 "Saves the data to the file located by the filename"279 print 'save this ', dicFilename280 281 if dicFilename['TYPE'] == 'SSH':282 sFile = dicFilename['TMPNAME']283 else:284 sFile = dicFilename['NAME']285 outfile = open(sFile, "w")286 if outfile:287 outfile.write(data)288 outfile.close() 289 #mark as unmodified since last save290 #self.textbuffer.set_modified(False)291 292 if dicFilename['TYPE'] == 'SSH':293 os.system('cp -f ' + dicFilename['TMPNAME'] +' ' + os.path.basename(dicFilename['NAME'] ) )294 s1 = 'scp -P ' + dicFilename['PORT'] + ' ' + os.path.basename(dicFilename['NAME'] ) + ' ' + dicFilename['USER'] + '@' + dicFilename['HOST'] + '://' 295 s1 += os.path.dirname(dicFilename['NAME'] )296 print s1297 298 os.system(s1)299 os.system('rm ' + os.path.basename(dicFilename['NAME'] ) )300 print 'Files saved' 301 def saveFile(self): 302 liEntry, liReport = self.reportValues.getEntries()303 304 # report Head305 sDoc = "<report>\n"306 if liReport:307 308 sDoc = self.addList(sDoc, liReport)309 310 311 312 # report header313 liEntry, liReport = self.reportHeaderDA.getEntries()314 if liReport:315 print liReport316 sDoc += "<reportHeader>\n"317 sDoc = self.addList(sDoc, liReport)318 319 if liEntry:320 #print liEntry321 #print sDoc 322 sDoc = self.addList(sDoc, liEntry, sEntry="entry")323 324 325 sDoc += "</reportHeader>\n" 326 327 328 #doc = self.dic2xml(doc, liEntry, "reportHeader")329 330 # Page Header331 liEntry, liReport = self.PageHeaderDA.getEntries()332 if liReport:333 print liReport334 sDoc += "<pageHeader>\n"335 sDoc = self.addList(sDoc, liReport)336 337 if liEntry:338 #print liEntry339 #print sDoc 340 sDoc = self.addList(sDoc, liEntry, sEntry="entry")341 342 343 sDoc += "</pageHeader>\n" 344 # page groups345 sDoc += "<groups>\n" 346 sDoc += "<count>" + `self.dicPage['count']` + "</count>"347 348 for k in range(len(self.reportGroupsDA)):349 liEntry, liReport = self.reportGroupsDA[k].getEntries()350 if liReport:351 print liReport352 353 354 355 if liEntry:356 #print liEntry357 #print sDoc 358 sDoc += "<groupEntry>\n"359 sDoc += "\t<number>" + `self.dicPage[`k` + '_groupNumber']` + "</number>\n"360 sDoc += "\t<resultSet>" + `self.dicPage[`k` + '_groupResultSet']` + "</resultSet>\n"361 sDoc += "\t<pageDetails>\n"362 sDoc += "\t\t<posX1>" + str(self.dicPage[`k` + '_detailsX1']) + "</posX1>\n"363 sDoc += "\t\t<posX2>" + str(self.dicPage[`k` + '_detailsX2']) + "</posX2>\n"364 sDoc += "\t\t<posY1>" + str(self.dicPage[`k` + '_detailsY1']) + "</posY1>\n"365 sDoc += "\t\t<posY2>" + str(self.dicPage[`k` + '_detailsY2']) + "</posY2>\n"366 sDoc += "\t\t<lineY>" + str(self.dicPage[`k` + '_detailslineY']) + "</lineY>\n"367 368 sDoc = self.addList(sDoc, liReport)369 370 sDoc = self.addList(sDoc, liEntry, sEntry="entry")371 372 sDoc += "</pageDetails>\n"373 sDoc += "</groupEntry>\n"374 375 376 sDoc += "</groups>\n" 377 378 # page Footer379 liEntry, liReport = self.PageFooterDA.getEntries()380 if liReport:381 print liReport382 sDoc += "\n<pageFooter>\n"383 sDoc = self.addList(sDoc, liReport)384 385 if liEntry:386 #print liEntry387 #print sDoc 388 sDoc = self.addList(sDoc, liEntry, sEntry="entry")389 390 391 sDoc += "</pageFooter>\n" 392 393 394 #doc = self.dic2xml(doc, liEntry, "reportHeader")395 396 397 # report Footer398 liEntry, liReport = self.reportFooterDA.getEntries()399 if liReport:400 print liReport401 sDoc += "\n<reportFooter>\n"402 sDoc = self.addList(sDoc, liReport)403 404 if liEntry:405 #print liEntry406 #print sDoc 407 sDoc = self.addList(sDoc, liEntry, sEntry="entry")408 409 410 sDoc += "</reportFooter>\n" 411 412 413 #doc = self.dic2xml(doc, liEntry, "reportHeader") 414 sDoc += "</report> "415 print sDoc416 self.save_file(self.dicCurrentFilename, sDoc)417 418 419 def addList(self, sDoc, liReport, sEntry=None):420 for i in liReport:421 if sEntry:422 423 sDoc += "\t<entry>\n"424 425 for key in ['name', 'posX1', 'posX2', 'posY1', 'posY2', 'class', 'value', 'type','resultSet', 'format', 'variable', 'memory', 'formula', 'property','font', 'fontsize', 'fontjustification', 'foregroundColor' , 'backgroundColor', 'grayScale']:426 if i.has_key(key):427 if sEntry:428 sDoc += "\t"429 430 sDoc += "\t<" + key +">"431 sValue = i[key]432 sValue = self.checkXmlValue(sValue)433 sDoc += sValue434 sDoc += "</" + key +">\n"435 436 sDoc += "\t</entry>\n"437 438 else:439 for key in i.keys():440 if sEntry:441 sDoc += "\t"442 sDoc += "\t<" + key +">"443 sValue = i[key]444 sValue = self.checkXmlValue(sValue)445 sDoc += sValue446 sDoc += "</" + key +">\n"447 return sDoc448 449 450 451 452 def readReportDocument(self, dicFilename):453 "Opens the file given in filename and reads it in"454 print 'dicFilename = ', dicFilename 455 if dicFilename['TYPE'] == 'SSH':456 dicFilename['TMPNAME'] = 'tmp_editor_ssh_tab_GUI_0' 457 s1 = 'scp -P ' + dicFilename['PORT'] + ' ' + dicFilename['USER'] + '@' + dicFilename['HOST'] + ':/' 458 s1 += dicFilename['NAME'] + ' ' + dicFilename['TMPNAME']459 print 's1 = ' , s1460 os.system(s1)461 filename = dicFilename['TMPNAME']462 463 else:464 465 filename = dicFilename['NAME']466 467 print 'filename to read xml', filename 468 doc = self.readDocument(filename)469 470 print `doc`471 cyRootNode = self.getRootNode(doc)472 473 self.setReportValues(cyRootNode)474 475 self.reportValues = drawingReport.drawingReport() 476 477 self.reportValues.setReportEntry({'topMargin':self.dicPage['topMargin']})478 self.reportValues.setReportEntry({'bottomMargin':self.dicPage['bottomMargin']})479 self.reportValues.setReportEntry({'rightMargin':self.dicPage['rightMargin']})480 self.reportValues.setReportEntry({'leftMargin':self.dicPage['leftMargin']})481 self.reportValues.setReportEntry({'papersizeX':self.dicPage['papersizeX']})482 self.reportValues.setReportEntry({'papersizeY':self.dicPage['papersizeY']})483 self.reportValues.setReportEntry({'orientation':self.dicPage['orientation']})484 if self.dicPage.has_key('SiteBackground_URL'):485 self.reportValues.setReportEntry({'SiteBackground_URL':self.dicPage['SiteBackground_URL']})486 self.reportValues.setReportEntry({'SiteBackgroundHeight':self.dicPage['SiteBackgroundHeight']})487 self.reportValues.setReportEntry({'SiteBackgroundWidth':self.dicPage['SiteBackgroundWidth']})488 self.reportValues.setReportEntry({'SiteBackgroundX':self.dicPage['SiteBackgroundX']})489 self.reportValues.setReportEntry({'SiteBackgroundY':self.dicPage['SiteBackgroundY']})490 491 if self.dicPage.has_key('SiteBackground_URL2'):492 self.reportValues.setReportEntry({'SiteBackground_URL2':self.dicPage['SiteBackground_URL2']})493 self.reportValues.setReportEntry({'SiteBackgroundHeight2':self.dicPage['SiteBackgroundHeight2']})494 self.reportValues.setReportEntry({'SiteBackgroundWidth2':self.dicPage['SiteBackgroundWidth2']})495 self.reportValues.setReportEntry({'SiteBackgroundX2':self.dicPage['SiteBackgroundX2']})496 self.reportValues.setReportEntry({'SiteBackgroundY2':self.dicPage['SiteBackgroundY2']})497 if self.dicPage.has_key('SiteBackground_URL3'):498 self.reportValues.setReportEntry({'SiteBackground_URL3':self.dicPage['SiteBackground_URL3']})499 self.reportValues.setReportEntry({'SiteBackgroundHeight3':self.dicPage['SiteBackgroundHeight3']})500 self.reportValues.setReportEntry({'SiteBackgroundWidth3':self.dicPage['SiteBackgroundWidth3']})501 self.reportValues.setReportEntry({'SiteBackgroundX3':self.dicPage['SiteBackgroundX3']})502 self.reportValues.setReportEntry({'SiteBackgroundY3':self.dicPage['SiteBackgroundY3']})503 cyReportHeaderNode = self.getNode(cyRootNode, 'reportHeader')504 #print 'node = ', cyReportHeaderNode[0].toxml()505 506 cyReportHeaderEntries = self.getNodes(cyReportHeaderNode[0], 'entry')507 508 509 if cyReportHeaderEntries:510 511 width = self.dicPage['headerX2'] - self.dicPage['headerX1'] 512 height = self.dicPage['headerY2'] - self.dicPage['headerY1']513 514 self.reportHeaderDA = drawingReport.drawingReport()515 self.reportHeaderDA.createDA( self.getWidget('scReportHeader'), self.getWidget('vpReportHeader'), self.getWidget('daReportHeader'), width, height)516 self.reportHeaderDA.setReportEntry({'posX1':self.dicPage['headerX1'] })517 self.reportHeaderDA.setReportEntry({'posX2':self.dicPage['headerX2'] })518 self.reportHeaderDA.setReportEntry({'posY1':self.dicPage['headerY1'] })519 self.reportHeaderDA.setReportEntry({'posY2':self.dicPage['headerY2'] })520 521 for i in cyReportHeaderEntries:522 523 print i.toxml()524 self.reportHeaderDA.setEntry(self.getXmlEntry(i))525 #print 'dicEntry = ', dicEntry526 527 528 cyReportPageHeaderNode = self.getNode(cyRootNode, 'pageHeader')529 cyPageHeaderEntries = self.getNodes(cyReportPageHeaderNode[0], 'entry')530 if cyPageHeaderEntries:531 532 width = self.dicPage['pageX2'] - self.dicPage['pageX1'] 533 height = self.dicPage['pageY2'] - self.dicPage['pageY1']534 535 self.PageHeaderDA = drawingReport.drawingReport()536 self.PageHeaderDA.createDA( self.getWidget('scPageHeader'), self.getWidget('vpPageHeader'), self.getWidget('daPageHeader'), width, height)537 self.PageHeaderDA.setReportEntry({'posX1':self.dicPage['pageX1'] })538 self.PageHeaderDA.setReportEntry({'posX2':self.dicPage['pageX2'] })539 self.PageHeaderDA.setReportEntry({'posY1':self.dicPage['pageY1'] })540 self.PageHeaderDA.setReportEntry({'posY2':self.dicPage['pageY2'] })541 542 for i in cyPageHeaderEntries:543 544 #print i.toxml()545 self.PageHeaderDA.setEntry(self.getXmlEntry(i))546 #print 'dicEntry = ', dicEntry547 548 549 cyReportGroupsNodes = self.getNode(cyRootNode, 'groups')550 551 552 553 if cyReportGroupsNodes:554 for k in range(len(cyReportGroupsNodes)):555 cyGroupsEntries = self.getNodes(cyReportGroupsNodes[k], 'entry')556 557 558 # cyPageDetailsNodes = self.getNodes(cyGroupEntry, 'pageDetails')559 # print'+++++++ cyPageDetailsNodes = ', cyPageDetailsNodes560 # 561 # for i in range(len(cyPageDetailsNodes)):562 width = self.dicPage[`k` + '_detailsX2'] - self.dicPage[`k` + '_detailsX1'] 563 height = self.dicPage[`k` + '_detailsY2'] - self.dicPage[`k` + '_detailsY1']564 565 self.reportGroupsDA.append(drawingReport.drawingReport())566 self.reportGroupsDA[k].createDA( self.getWidget('scGroups'), self.getWidget('vpGroups'), self.getWidget('daGroups'), width, height)567 self.reportGroupsDA[k].setReportEntry({'posX1':self.dicPage[`k` + '_detailsX1'] })568 self.reportGroupsDA[k].setReportEntry({'posX2':self.dicPage[`k` + '_detailsX2'] })569 self.reportGroupsDA[k].setReportEntry({'posY1':self.dicPage[`k` + '_detailsY1'] })570 self.reportGroupsDA[k].setReportEntry({'posY2':self.dicPage[`k` + '_detailsY2'] })571 self.reportGroupsDA[k].setReportEntry({'posY2':self.dicPage[`k` + '_detailsY2'] })572 self.reportGroupsDA[k].setReportEntry({'lineY':self.dicPage[`k` + '_detailslineY'] })573 #print cyGroupEntry.toxml()574 575 for i in cyGroupsEntries:576 #print i.toxml()577 self.reportGroupsDA[k].setEntry(self.getXmlEntry(i))578 #print 'dicEntry = ', dicEntry579 580 cyReportPageFooterNode = self.getNode(cyRootNode, 'pageFooter')581 cyPageFooterEntries = self.getNodes(cyReportPageFooterNode[0], 'entry')582 if cyPageFooterEntries:583 584 width = self.dicPage['pageFooterX2'] - self.dicPage['pageFooterX1'] 585 height = self.dicPage['pageFooterY2'] - self.dicPage['pageFooterY1']586 587 self.PageFooterDA = drawingReport.drawingReport()588 self.PageFooterDA.createDA( self.getWidget('scPageFooter'), self.getWidget('vpPageFooter'), self.getWidget('daPageFooter'), width, height)589 self.PageFooterDA.setReportEntry({'posX1':self.dicPage['pageFooterX1'] })590 self.PageFooterDA.setReportEntry({'posX2':self.dicPage['pageFooterX2'] })591 self.PageFooterDA.setReportEntry({'posY1':self.dicPage['pageFooterY1'] })592 self.PageFooterDA.setReportEntry({'posY2':self.dicPage['pageFooterY2'] })593 594 for i in cyPageFooterEntries:595 596 #print i.toxml()597 self.PageFooterDA.setEntry(self.getXmlEntry(i))598 #print 'dicEntry = ', dicEntry599 cyReportFooterNode = self.getNode(cyRootNode, 'reportFooter')600 601 cyReportFooterEntries = self.getNodes(cyReportFooterNode[0], 'entry')602 603 604 if cyReportFooterEntries:605 606 width = self.dicPage['footerX2'] - self.dicPage['footerX1'] 607 height = self.dicPage['footerY2'] - self.dicPage['footerY1']608 609 self.reportFooterDA = drawingReport.drawingReport()610 self.reportFooterDA.createDA( self.getWidget('scReportFooter'), self.getWidget('vpReportFooter'), self.getWidget('daReportFooter'), width, height)611 self.reportFooterDA.setReportEntry({'posX1':self.dicPage['footerX1'] })612 self.reportFooterDA.setReportEntry({'posX2':self.dicPage['footerX2'] })613 self.reportFooterDA.setReportEntry({'posY1':self.dicPage['footerY1'] })614 self.reportFooterDA.setReportEntry({'posY2':self.dicPage['footerY2'] })615 for i in cyReportFooterEntries:616 617 #print i.toxml()618 self.reportFooterDA.setEntry(self.getXmlEntry(i))619 #print 'dicEntry = ', dicEntry620 621 622 def getXmlEntry(self, cyNode):623 624 dicEntry = {}625 # set some defaults626 dicEntry['Property'] = '0'627 628 dicEntry['name'] = self.getEntrySpecification(cyNode,'name').encode('ascii')629 try:630 dicEntry['width'] = int(self.getEntrySpecification(cyNode,'width'))631 except:632 dicEntry['width'] = 0633 try:634 dicEntry['height'] = int(self.getEntrySpecification(cyNode,'height'))635 except:636 dicEntry['height'] = 0637 638 dicEntry['posX1'] = int(self.getEntrySpecification(cyNode,'posX1'))639 dicEntry['posX2'] = int(self.getEntrySpecification(cyNode,'posX2'))640 dicEntry['posY1'] = int(self.getEntrySpecification(cyNode,'posY1'))641 dicEntry['posY2'] = int(self.getEntrySpecification(cyNode,'posY2'))642 643 dicEntry['type'] = self.getEntrySpecification(cyNode,'type').encode('ascii')644 645 dicEntry['class'] = self.getEntrySpecification(cyNode,'class').encode('utf-8')646 dicEntry['value'] = self.getEntrySpecification(cyNode,'value')647 dicEntry['format'] = self.getEntrySpecification(cyNode,'format')648 if dicEntry['format']:649 dicEntry['format'] = dicEntry['format'].encode('ascii')650 dicEntry['formula'] = self.getEntrySpecification(cyNode,'formula')651 if dicEntry['formula']:652 dicEntry['formula'] = dicEntry['formula'].encode('utf-8')653 else:654 dicEntry['formula'] = None655 dicEntry['memory'] = self.getEntrySpecification(cyNode,'memory')656 if dicEntry['memory']:657 dicEntry['memory'] = dicEntry['memory'].encode('ascii')658 else:659 dicEntry['memory'] = None660 661 dicEntry['type'] = self.getEntrySpecification(cyNode,'type')662 sResultSet = self.getEntrySpecification(cyNode,'resultSet')663 if sResultSet:664 sResultSet = sResultSet.encode('ascii')665 dicEntry['resultSet'] = sResultSet666 else:667 dicEntry['resultSet'] = 'zero'668 sVariable = self.getEntrySpecification(cyNode,'variable')669 if sVariable:670 sVariable = sVariable.encode('ascii')671 dicEntry['variable'] = sVariable672 else:673 dicEntry['variable'] = None 674 675 sFont = self.getEntrySpecification(cyNode,'font')676 liFont = sFont.split(';')677 678 dicEntry['font'] = liFont[0]679 if len(liFont)> 1:680 if liFont[1] == 'TTF':681 print liFont[0], type(liFont[0])682 print liFont[2], type(liFont[2])683 pdfmetrics.registerFont( TTFont( liFont[0].encode('ascii'),liFont[2].encode('ascii')))684 685 dicEntry['fontsize'] = int( self.getEntrySpecification(cyNode,'fontsize'))686 sColor = self.getEntrySpecification(cyNode,'foregroundColor').encode('ascii')687 #print sColor688 iFind = sColor.find(',')689 # print iFind690 rColor = float(sColor[0:iFind])691 iFind2 = sColor.find(',', iFind+1)692 gColor = float(sColor[iFind+1:iFind2])693 bColor = float(sColor[iFind2+1:len(sColor)])694 695 dicEntry['foregroundColor'] = {'rColor' : rColor, 'gColor' : gColor, 'bColor' : bColor}696 #print dicEntry['foregroundColor']697 698 sColor = self.getEntrySpecification(cyNode,'backgroundColor').encode('ascii')699 #print sColor700 iFind = sColor.find(',')701 # print iFind702 rColor = float(sColor[0:iFind])703 iFind2 = sColor.find(',', iFind+1)704 gColor = float(sColor[iFind+1:iFind2])705 bColor = float(sColor[iFind2+1:len(sColor)])706 707 dicEntry['backgroundColor'] = {'rColor' : rColor, 'gColor' : gColor, 'bColor' : bColor}708 sGray = self.getEntrySpecification(cyNode,'grayScale')709 if sGray:710 dicEntry['grayScale'] = float(sGray.encode('ascii'))711 else:712 dicEntry['grayScale'] = 0.0713 714 fj = self.getEntrySpecification(cyNode,'fontJustification')715 if fj:716 fj = fj.encode('ascii')717 dicEntry['fontjustification'] = fj718 else:719 dicEntry['fontjustification'] = None720 dicEntry['property'] = self.getEntrySpecification(cyNode,'property')721 722 723 return dicEntry724 725 726 def setReportValues(self, cyRootNode):727 # Papersizes728 729 self.dicPage['topMargin'] = int(self.getEntrySpecification(cyRootNode[0],'topMargin'))730 self.dicPage['bottomMargin'] = int(self.getEntrySpecification(cyRootNode[0],'bottomMargin'))731 self.dicPage['leftMargin'] = int(self.getEntrySpecification(cyRootNode[0],'leftMargin'))732 self.dicPage['rightMargin'] = int(self.getEntrySpecification(cyRootNode[0],'rightMargin'))733 734 sPapersize = 'A4'735 try:736 sPapersize = self.getEntrySpecification(cyRootNode[0],'paperSize')737 except:738 sPapersize = 'A4'739 if sPapersize == 'A5':740 self.dicText['Papersize'] = self.pagesizes['A5']741 elif sPapersize == 'A6':742 self.dicText['Papersize'] = self.pagesizes['A6']743 else:744 self.dicText['Papersize'] = self.pagesizes['A4']745 746 747 self.dicPage['orientation'] = self.getEntrySpecification(cyRootNode[0],'orientation').encode('ascii')748 if self.dicPage['orientation'] =='Portrait':749 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))750 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))751 elif self.dicPage['orientation'] =='Landscape':752 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))753 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))754 else:755 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))756 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))757 758 try:759 760 self.dicPage['SiteBackground_URL'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url').encode('ascii')761 self.dicPage['SiteBackgroundX'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x'))762 self.dicPage['SiteBackgroundY'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y'))763 self.dicPage['SiteBackgroundWidth'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width'))764 self.dicPage['SiteBackgroundHeight'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height'))765 self.dicPage['PropertyBG'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG')766 except Exception, params:767 print Exception, params768 769 try:770 771 self.dicPage['SiteBackground_URL2'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url2').encode('ascii')772 self.dicPage['SiteBackgroundX2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x2'))773 self.dicPage['SiteBackgroundY2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y2'))774 self.dicPage['SiteBackgroundWidth2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width2'))775 self.dicPage['SiteBackgroundHeight2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height2'))776 self.dicPage['PropertyBG2'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG2')777 except Exception, params:778 print Exception, params779 780 try:781 782 self.dicPage['SiteBackground_URL3'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url3').encode('ascii')783 self.dicPage['SiteBackgroundX3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x3'))784 self.dicPage['SiteBackgroundY3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y3'))785 self.dicPage['SiteBackgroundWidth3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width3'))786 self.dicPage['SiteBackgroundHeight3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height3'))787 self.dicPage['PropertyBG3'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG3')788 except Exception, params:789 print Exception, params790 791 792 793 #794 # Report Header795 #796 cyReportHeaderNode = self.getNode(cyRootNode, 'reportHeader')797 #print '------------------'798 #print cyReportHeaderNode799 #print cyReportHeaderNode[0].toxml()800 801 cyReportHeaderEntries = self.getNodes(cyReportHeaderNode[0], 'entry')802 #print '+++++++'803 #print cyReportHeaderEntries804 liRecord = []805 self.dicPage['headerX1'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posX1'))806 self.dicPage['headerX2'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posX2'))807 self.dicPage['headerY1'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posY1'))808 self.dicPage['headerY2'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posY2'))809 self.dicPage['beginReportHeaderX'] = self.dicPage['leftMargin'] + self.dicPage['headerX1']810 self.dicPage['endReportHeaderX'] = self.dicPage['headerX2']811 812 self.dicPage['beginReportHeaderY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY1']813 self.dicPage['endReportHeaderY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY2']814 self.dicPage['beginReportFooterX'] = self.dicPage['leftMargin'] 815 self.dicPage['endReportFooterX'] = self.dicPage['papersizeX'] - self.dicPage['rightMargin']816 817 self.dicPage['beginReportFooterY'] = self.dicPage['bottomMargin'] 818 self.dicPage['endReportFooterY'] = self.dicPage['bottomMargin'] 819 #820 # PageHeader821 #822 cyReportPageNode = self.getNode(cyRootNode, 'pageHeader')823 #print '------------------'824 #print cyReportPageNode825 #print cyReportPageNode[0].toxml()826 827 cyReportPageEntries = self.getNodes(cyReportPageNode[0], 'entry')828 #print '+++++++'829 #print cyReportPageEntries830 liRecord = []831 self.dicPage['pageX1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX1'))832 self.dicPage['pageX2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX2'))833 self.dicPage['pageY1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY1'))834 self.dicPage['pageY2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY2'))835 self.dicPage['beginPageHeaderX'] = self.dicPage['leftMargin'] + self.dicPage['pageX1']836 self.dicPage['endPageHeaderX'] = self.dicPage['pageX2']837 self.dicPage['beginPageHeaderY'] = self.dicPage['endReportHeaderY'] - self.dicPage['pageY1']838 self.dicPage['endPageHeaderY'] = self.dicPage['endReportHeaderY'] - self.dicPage['pageY2']839 840 841 #842 # Report-footer843 #844 cyReportFooterNode = self.getNode(cyRootNode, 'reportFooter')845 #print '------------------'846 #print cyReportFooterNode847 #print cyReportFooterNode[0].toxml()848 849 cyReportFooterEntries = self.getNodes(cyReportFooterNode[0], 'entry')850 #print '+++++++'851 #print cyReportFooterEntries852 liRecord = []853 854 self.dicPage['footerX1'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posX1'))855 self.dicPage['footerX2'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posX2'))856 self.dicPage['footerY1'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posY1'))857 self.dicPage['footerY2'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posY2'))858 try:859 self.dicPage['ReportFootAppendToGroup'] = int(self.getEntrySpecification(cyReportFooterNode[0],'appendtogroup'))860 except:861 self.dicPage['ReportFootAppendToGroup'] = 0862 863 self.dicPage['beginReportFooterX'] = self.dicPage['leftMargin'] + self.dicPage['footerX1']864 self.dicPage['endReportFooterX'] = self.dicPage['footerX2']865 866 self.dicPage['beginReportFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['footerY1']867 self.dicPage['endReportFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['footerY2']868 869 #870 # Page -footer871 #872 cyReportPageNode = self.getNode(cyRootNode, 'pageFooter')873 874 #print '------------------'875 #print cyReportPageNode876 #print cyReportPageNode[0].toxml()877 878 cyReportPageEntries = self.getNodes(cyReportPageNode[0], 'entry')879 #print '+++++++'880 #print cyReportPageEntries881 liRecord = []882 self.dicPage['pageFooterX1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX1'))883 self.dicPage['pageFooterX2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX2'))884 self.dicPage['pageFooterY1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY1'))885 self.dicPage['pageFooterY2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY2'))886 try:887 self.dicPage['PageFootAppendToGroup'] = int(self.getEntrySpecification(cyReportPageNode[0],'appendtogroup'))888 except:889 self.dicPage['PageFootAppendToGroup'] = 0890 891 self.dicPage['beginPageFooterX'] = self.dicPage['leftMargin'] + self.dicPage['pageFooterX1']892 self.dicPage['endPageFooterX'] = self.dicPage['pageFooterX2']893 self.dicPage['beginPageFooterY'] = self.dicPage['pageFooterY2'] + self.dicPage['bottomMargin'] + self.dicPage['pageFooterY1']894 self.dicPage['beginPageFooterY_LastPage'] = self.dicPage['endReportFooterY'] + self.dicPage['pageFooterY2']895 self.dicPage['endPageFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['pageFooterY1']896 self.dicPage['PrintRangeFirstSite'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['bottomMargin'] -self.dicPage['headerY1'] - self.dicPage['headerY2'] - self.dicPage['pageY1'] - self.dicPage['pageY2'] - self.dicPage['pageFooterY1'] - self.dicPage['pageFooterY2'] 897 self.dicPage['PrintRangeNextSites'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['bottomMargin'] - self.dicPage['pageY1'] - self.dicPage['pageY2'] - self.dicPage['pageFooterY1'] - self.dicPage['pageFooterY2'] 898 899 self.dicPage['beginPageHeaderOtherSitesY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['pageY1'] 900 self.dicPage['endPageHeaderOtherSitesY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['pageY2']901 #902 # calculate Sides903 #904 print "Side Values = ", self.dicPage['papersizeY'] , self.dicPage['topMargin'] , self.dicPage['headerY2'] , self.dicPage['endPageFooterY'] , self.dicPage['bottomMargin'] , self.dicPage['pageFooterY1']905 self.dicPage['reportDetailsY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY2'] - self.dicPage['bottomMargin'] - self.dicPage['pageFooterY2']906 907 908 909 910 911 #print "appendtogroup page, report = ", self.dicPage['PageFootAppendToGroup'] , self.dicPage['ReportFootAppendToGroup'] 912 913 cyGroupNode = self.getNode(cyRootNode, 'groups')914 915 self.dicPage['count'] = self.getEntrySpecification(cyGroupNode[0],'count')916 cyGroupEntries = self.getNodes(cyGroupNode[0], 'groupEntry')917 #print cyGroupEntries918 for k in range(len(cyGroupEntries)):919 cyGroupEntry = cyGroupEntries[k]920 self.dicPage[`k` + '_ChangeGroupBy'] = self.getEntrySpecification(cyGroupEntry,'changeGroupBy')921 self.dicPage[`k` + '_groupNumber'] = int(self.getEntrySpecification(cyGroupEntry,'number'))922 self.dicPage[`k` + '_groupResultSet'] = self.getEntrySpecification(cyGroupEntry,'resultSet')923 924 cyPageDetailsNodes = self.getNodes(cyGroupEntry, 'pageDetails')925 print'+++++++ cyPageDetailsNodes = ', cyPageDetailsNodes926 927 for i in range(len(cyPageDetailsNodes)):928 cyReportDetailsNode = cyPageDetailsNodes[i]929 cyReportDetailsEntries = self.getNodes(cyReportDetailsNode, 'entry')930 931 self.dicPage[`i` + '_detailsX1'] = int(self.getEntrySpecification(cyReportDetailsNode,'posX1'))932 self.dicPage[`i` + '_detailsX2'] = int(self.getEntrySpecification(cyReportDetailsNode,'posX2'))933 self.dicPage[`i` + '_detailsY1'] = int(self.getEntrySpecification(cyReportDetailsNode,'posY1'))934 self.dicPage[`i` + '_detailsY2'] = int(self.getEntrySpecification(cyReportDetailsNode,'posY2'))935 self.dicPage[`i` + '_detailslineY'] = int(self.getEntrySpecification(cyReportDetailsNode,'lineY'))...

Full Screen

Full Screen

permmod.py

Source:permmod.py Github

copy

Full Screen

...802 803 def test_public_for_all_staff(self):804 request = self.get_request()805 request.user.is_staff = True806 page = Page()807 page.pk = 1808 self.assertTrue(page.has_view_permission(request))809 def test_public_for_all_staff_assert_num_queries(self):810 request = self.get_request()811 request.user.is_staff = True812 page = Page()813 page.pk = 1814 with self.assertNumQueries(0):815 page.has_view_permission(request)816 def test_public_for_all(self):817 user = User.objects.create_user('user', 'user@domain.com', 'user')818 request = self.get_request(user)819 page = Page()820 page.pk = 1821 page.level = 0822 page.tree_id = 1823 self.assertTrue(page.has_view_permission(request))824 def test_public_for_all_num_queries(self):825 user = User.objects.create_user('user', 'user@domain.com', 'user')826 request = self.get_request(user)827 site = Site()828 site.pk = 1829 page = Page()830 page.pk = 1831 page.level = 0832 page.tree_id = 1833 with self.assertNumQueries(3):834 """835 The queries are:836 The current Site837 PagePermission query for affected pages838 GlobalpagePermission query for user839 """840 page.has_view_permission(request)841 842 def test_unauthed(self):843 request = self.get_request()844 page = Page()845 page.pk = 1846 page.level = 0847 page.tree_id = 1848 self.assertTrue(page.has_view_permission(request))849 850 def test_unauthed_num_queries(self):851 request = self.get_request()852 site = Site()853 site.pk = 1854 page = Page()855 page.pk = 1856 page.level = 0857 page.tree_id = 1858 with self.assertNumQueries(1):859 """860 The query is:861 PagePermission query for affected pages862 """863 page.has_view_permission(request)864 865 def test_authed_basic_perm(self):866 with SettingsOverride(CMS_PUBLIC_FOR='staff'):867 user = User.objects.create_user('user', 'user@domain.com', 'user')868 user.user_permissions.add(Permission.objects.get(codename='view_page'))869 request = self.get_request(user)870 page = Page()871 page.pk = 1872 page.level = 0873 page.tree_id = 1874 self.assertTrue(page.has_view_permission(request))875 876 def test_authed_basic_perm_num_queries(self):877 site = Site()878 site.pk = 1879 with SettingsOverride(CMS_PUBLIC_FOR='staff'):880 user = User.objects.create_user('user', 'user@domain.com', 'user')881 user.user_permissions.add(Permission.objects.get(codename='view_page'))882 request = self.get_request(user)883 page = Page()884 page.pk = 1885 page.level = 0886 page.tree_id = 1887 with self.assertNumQueries(5):888 """889 The queries are:890 The site891 PagePermission query for affected pages892 GlobalpagePermission query for user893 Generic django permission lookup894 content type lookup by permission lookup895 """896 page.has_view_permission(request)897 898 def test_authed_no_access(self):899 with SettingsOverride(CMS_PUBLIC_FOR='staff'):900 user = User.objects.create_user('user', 'user@domain.com', 'user')901 request = self.get_request(user)902 page = Page()903 page.pk = 1904 page.level = 0905 page.tree_id = 1906 self.assertFalse(page.has_view_permission(request))907 908 def test_unauthed_no_access(self):909 with SettingsOverride(CMS_PUBLIC_FOR='staff'):910 request = self.get_request()911 page = Page()912 page.pk = 1913 page.level = 0914 page.tree_id = 1915 self.assertFalse(page.has_view_permission(request))916 917 def test_unauthed_no_access_num_queries(self):918 site = Site()919 site.pk = 1920 request = self.get_request()921 page = Page()922 page.pk = 1923 page.level = 0924 page.tree_id = 1925 with self.assertNumQueries(1):926 page.has_view_permission(request)927 928 def test_page_permissions(self):929 with SettingsOverride(CMS_PUBLIC_FOR='staff'):930 user = User.objects.create_user('user', 'user@domain.com', 'user')931 request = self.get_request(user)932 page = create_page('A', 'nav_playground.html', 'en')933 PagePermission.objects.create(can_view=True, user=user, page=page)934 self.assertTrue(page.has_view_permission(request))935 936 def test_page_permissions_view_groups(self):937 with SettingsOverride(CMS_PUBLIC_FOR='staff'):938 user = User.objects.create_user('user', 'user@domain.com', 'user')939 group = Group.objects.create(name='testgroup')940 group.user_set.add(user)941 request = self.get_request(user)942 page = create_page('A', 'nav_playground.html', 'en')943 PagePermission.objects.create(can_view=True, group=group, page=page)944 self.assertTrue(page.has_view_permission(request))945 946 def test_global_permission(self):947 with SettingsOverride(CMS_PUBLIC_FOR='staff'):948 user = User.objects.create_user('user', 'user@domain.com', 'user')949 GlobalPagePermission.objects.create(can_view=True, user=user)950 request = self.get_request(user)951 page = Page()952 page.pk = 1953 page.level = 0954 page.tree_id = 1...

Full Screen

Full Screen

page.py

Source:page.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from __future__ import with_statement3from cms.admin.forms import PageForm4from cms.api import create_page5from cms.models import Page, Title6from cms.models.placeholdermodel import Placeholder7from cms.models.pluginmodel import CMSPlugin8from cms.plugins.text.models import Text9from cms.sitemaps import CMSSitemap10from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PAGE, 11 URL_CMS_PAGE_ADD)12from cms.test_utils.util.context_managers import (LanguageOverride, 13 SettingsOverride)14from cms.utils.page_resolver import get_page_from_request15from django.conf import settings16from django.contrib.auth.models import User17from django.contrib.sites.models import Site18from django.core.urlresolvers import reverse19from django.http import HttpRequest, HttpResponse, HttpResponseNotFound20import datetime21import os.path22class PagesTestCase(CMSTestCase):23 24 def test_add_page(self):25 """26 Test that the add admin page could be displayed via the admin27 """28 superuser = self.get_superuser()29 with self.login_user_context(superuser):30 response = self.client.get(URL_CMS_PAGE_ADD)31 self.assertEqual(response.status_code, 200)32 def test_create_page(self):33 """34 Test that a page can be created via the admin35 """36 page_data = self.get_new_page_data()37 superuser = self.get_superuser()38 with self.login_user_context(superuser):39 response = self.client.post(URL_CMS_PAGE_ADD, page_data)40 self.assertRedirects(response, URL_CMS_PAGE)41 title = Title.objects.get(slug=page_data['slug'])42 self.assertNotEqual(title, None)43 page = title.page44 page.published = True45 page.save()46 self.assertEqual(page.get_title(), page_data['title'])47 self.assertEqual(page.get_slug(), page_data['slug'])48 self.assertEqual(page.placeholders.all().count(), 2)49 50 # were public instanes created?51 title = Title.objects.drafts().get(slug=page_data['slug'])52 53 def test_slug_collision(self):54 """55 Test a slug collision56 """57 page_data = self.get_new_page_data()58 # create first page59 superuser = self.get_superuser()60 with self.login_user_context(superuser):61 response = self.client.post(URL_CMS_PAGE_ADD, page_data)62 self.assertRedirects(response, URL_CMS_PAGE)63 64 #page1 = Title.objects.get(slug=page_data['slug']).page65 # create page with the same page_data66 67 response = self.client.post(URL_CMS_PAGE_ADD, page_data)68 69 if settings.i18n_installed:70 self.assertEqual(response.status_code, 302)71 # did we got right redirect?72 self.assertEqual(response['Location'].endswith(URL_CMS_PAGE), True)73 else:74 self.assertEqual(response.status_code, 200)75 self.assertEqual(response['Location'].endswith(URL_CMS_PAGE_ADD), True)76 # TODO: check for slug collisions after move77 # TODO: check for slug collisions with different settings 78 79 def test_details_view(self):80 """81 Test the details view82 """83 superuser = self.get_superuser()84 with self.login_user_context(superuser):85 response = self.client.get(self.get_pages_root())86 self.assertEqual(response.status_code, 404)87 page = create_page('test page 1', "nav_playground.html", "en")88 response = self.client.get(self.get_pages_root())89 self.assertEqual(response.status_code, 404)90 self.assertTrue(page.publish())91 create_page("test page 2", "nav_playground.html", "en", 92 parent=page, published=True)93 homepage = Page.objects.get_home()94 self.assertTrue(homepage.get_slug(), 'test-page-1')95 response = self.client.get(self.get_pages_root())96 self.assertEqual(response.status_code, 200)97 def test_edit_page(self):98 """99 Test that a page can edited via the admin100 """101 superuser = self.get_superuser()102 with self.login_user_context(superuser):103 page_data = self.get_new_page_data()104 response = self.client.post(URL_CMS_PAGE_ADD, page_data)105 page = Page.objects.get(title_set__slug=page_data['slug'])106 response = self.client.get('/admin/cms/page/%s/' %page.id)107 self.assertEqual(response.status_code, 200)108 page_data['title'] = 'changed title'109 response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)110 self.assertRedirects(response, URL_CMS_PAGE)111 self.assertEqual(page.get_title(), 'changed title')112 113 def test_meta_description_and_keywords_fields_from_admin(self):114 """115 Test that description and keywords tags can be set via the admin116 """117 superuser = self.get_superuser()118 with self.login_user_context(superuser):119 page_data = self.get_new_page_data()120 page_data["meta_description"] = "I am a page"121 page_data["meta_keywords"] = "page,cms,stuff"122 response = self.client.post(URL_CMS_PAGE_ADD, page_data)123 page = Page.objects.get(title_set__slug=page_data['slug'])124 response = self.client.get('/admin/cms/page/%s/' %page.id)125 self.assertEqual(response.status_code, 200)126 page_data['meta_description'] = 'I am a duck'127 response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)128 self.assertRedirects(response, URL_CMS_PAGE)129 page = Page.objects.get(title_set__slug=page_data["slug"])130 self.assertEqual(page.get_meta_description(), 'I am a duck')131 self.assertEqual(page.get_meta_keywords(), 'page,cms,stuff')132 def test_meta_description_and_keywords_from_template_tags(self):133 from django import template134 superuser = self.get_superuser()135 with self.login_user_context(superuser):136 page_data = self.get_new_page_data()137 page_data["title"] = "Hello"138 page_data["meta_description"] = "I am a page"139 page_data["meta_keywords"] = "page,cms,stuff"140 self.client.post(URL_CMS_PAGE_ADD, page_data)141 page = Page.objects.get(title_set__slug=page_data['slug'])142 self.client.post('/admin/cms/page/%s/' %page.id, page_data)143 t = template.Template("{% load cms_tags %}{% page_attribute title %} {% page_attribute meta_description %} {% page_attribute meta_keywords %}")144 req = HttpRequest()145 page.published = True146 page.save()147 req.current_page = page 148 req.REQUEST = {}149 self.assertEqual(t.render(template.Context({"request": req})), "Hello I am a page page,cms,stuff")150 151 152 def test_copy_page(self):153 """154 Test that a page can be copied via the admin155 """156 page_a = create_page("page_a", "nav_playground.html", "en")157 page_a_a = create_page("page_a_a", "nav_playground.html", "en",158 parent=page_a)159 create_page("page_a_a_a", "nav_playground.html", "en", parent=page_a_a)160 161 page_b = create_page("page_b", "nav_playground.html", "en")162 page_b_a = create_page("page_b", "nav_playground.html", "en", 163 parent=page_b)164 165 count = Page.objects.drafts().count()166 167 superuser = self.get_superuser()168 with self.login_user_context(superuser):169 self.copy_page(page_a, page_b_a)170 171 self.assertEqual(Page.objects.drafts().count() - count, 3)172 173 174 def test_language_change(self):175 superuser = self.get_superuser()176 with self.login_user_context(superuser):177 page_data = self.get_new_page_data()178 self.client.post(URL_CMS_PAGE_ADD, page_data)179 pk = Page.objects.all()[0].pk180 response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"en" })181 self.assertEqual(response.status_code, 200)182 response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"de" })183 self.assertEqual(response.status_code, 200)184 185 def test_move_page(self):186 superuser = self.get_superuser()187 with self.login_user_context(superuser):188 page_data1 = self.get_new_page_data()189 self.client.post(URL_CMS_PAGE_ADD, page_data1)190 page_data2 = self.get_new_page_data()191 self.client.post(URL_CMS_PAGE_ADD, page_data2)192 page_data3 = self.get_new_page_data()193 self.client.post(URL_CMS_PAGE_ADD, page_data3)194 page1 = Page.objects.all()[0]195 page2 = Page.objects.all()[1]196 page3 = Page.objects.all()[2]197 # move pages198 response = self.client.post("/admin/cms/page/%s/move-page/" % page3.pk, {"target": page2.pk, "position": "last-child"})199 self.assertEqual(response.status_code, 200)200 response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "last-child"})201 self.assertEqual(response.status_code, 200)202 # check page2 path and url203 page2 = Page.objects.get(pk=page2.pk)204 self.assertEqual(page2.get_path(), page_data1['slug']+"/"+page_data2['slug'])205 self.assertEqual(page2.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/")206 # check page3 path and url207 page3 = Page.objects.get(pk=page3.pk)208 self.assertEqual(page3.get_path(), page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug'])209 self.assertEqual(page3.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug']+"/")210 # publish page 1 (becomes home)211 page1 = Page.objects.get(pk=page1.pk)212 page1.publish()213 public_page1 = page1.publisher_public214 self.assertEqual(public_page1.get_path(), '')215 # check that page2 and page3 url have changed216 page2 = Page.objects.get(pk=page2.pk)217 page2.publish()218 public_page2 = page2.publisher_public219 self.assertEqual(public_page2.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/")220 page3 = Page.objects.get(pk=page3.pk)221 page3.publish()222 public_page3 = page3.publisher_public223 self.assertEqual(public_page3.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/"+page_data3['slug']+"/")224 # move page2 back to root and check path of 2 and 3225 response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "right"})226 self.assertEqual(response.status_code, 200)227 page1 = Page.objects.get(pk=page1.pk)228 self.assertEqual(page1.get_path(), page_data1['slug'])229 page2 = Page.objects.get(pk=page2.pk)230 self.assertEqual(page2.get_path(), page_data2['slug'])231 page3 = Page.objects.get(pk=page3.pk)232 self.assertEqual(page3.get_path(), page_data2['slug']+"/"+page_data3['slug'])233 234 def test_move_page_inherit(self):235 parent = create_page("Parent", 'col_three.html', "en")236 child = create_page("Child", settings.CMS_TEMPLATE_INHERITANCE_MAGIC,237 "en", parent=parent)238 self.assertEqual(child.get_template(), parent.get_template())239 child.move_page(parent, 'left')240 self.assertEqual(child.get_template(), parent.get_template())241 242 243 def test_add_placeholder(self):244 # create page245 page = create_page("Add Placeholder", "nav_playground.html", "en",246 position="last-child", published=True, in_navigation=True)247 page.template = 'add_placeholder.html'248 page.save()249 url = page.get_absolute_url()250 response = self.client.get(url)251 self.assertEqual(200, response.status_code)252 path = os.path.join(settings.PROJECT_DIR, 'templates', 'add_placeholder.html')253 f = open(path, 'r')254 old = f.read()255 f.close()256 new = old.replace(257 '<!-- SECOND_PLACEHOLDER -->',258 '{% placeholder second_placeholder %}'259 )260 f = open(path, 'w')261 f.write(new)262 f.close()263 response = self.client.get(url)264 self.assertEqual(200, response.status_code)265 f = open(path, 'w')266 f.write(old)267 f.close()268 def test_sitemap_login_required_pages(self):269 """270 Test that CMSSitemap object contains only published,public (login_required=False) pages271 """272 create_page("page", "nav_playground.html", "en", login_required=True,273 published=True, in_navigation=True)274 self.assertEqual(CMSSitemap().items().count(),0)275 def test_edit_page_other_site_and_language(self):276 """277 Test that a page can edited via the admin when your current site is278 different from the site you are editing and the language isn't available279 for the current site.280 """281 site = Site.objects.create(domain='otherlang', name='otherlang')282 # Change site for this session283 page_data = self.get_new_page_data()284 page_data['site'] = site.pk285 page_data['title'] = 'changed title'286 TESTLANG = settings.CMS_SITE_LANGUAGES[site.pk][0]287 page_data['language'] = TESTLANG288 superuser = self.get_superuser()289 with self.login_user_context(superuser):290 response = self.client.post(URL_CMS_PAGE_ADD, page_data)291 self.assertRedirects(response, URL_CMS_PAGE)292 page = Page.objects.get(title_set__slug=page_data['slug'])293 with LanguageOverride(TESTLANG):294 self.assertEqual(page.get_title(), 'changed title')295 296 def test_flat_urls(self):297 with SettingsOverride(CMS_FLAT_URLS=True):298 home_slug = "home"299 child_slug = "child"300 grandchild_slug = "grandchild"301 home = create_page(home_slug, "nav_playground.html", "en",302 published=True, in_navigation=True)303 home.publish()304 child = create_page(child_slug, "nav_playground.html", "en",305 parent=home, published=True, in_navigation=True)306 child.publish()307 grandchild = create_page(grandchild_slug, "nav_playground.html", "en",308 parent=child, published=True, in_navigation=True)309 grandchild.publish()310 response = self.client.get(home.get_absolute_url())311 self.assertEqual(response.status_code, 200)312 response = self.client.get(child.get_absolute_url())313 self.assertEqual(response.status_code, 200)314 response = self.client.get(grandchild.get_absolute_url())315 self.assertEqual(response.status_code, 200)316 self.assertFalse(child.get_absolute_url() in grandchild.get_absolute_url())317 def test_templates(self):318 """319 Test the inheritance magic for templates320 """321 parent = create_page("parent", "nav_playground.html", "en")322 child = create_page("child", "nav_playground.html", "en", parent=parent)323 child.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC324 child.save()325 self.assertEqual(child.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)326 self.assertEqual(parent.get_template_name(), child.get_template_name())327 parent.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC328 parent.save()329 self.assertEqual(parent.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)330 self.assertEqual(parent.get_template(), settings.CMS_TEMPLATES[0][0])331 self.assertEqual(parent.get_template_name(), settings.CMS_TEMPLATES[0][1])332 333 def test_delete_with_plugins(self):334 """335 Check that plugins and placeholders get correctly deleted when we delete336 a page!337 """338 page = create_page("page", "nav_playground.html", "en")339 page.rescan_placeholders() # create placeholders340 placeholder = page.placeholders.all()[0]341 plugin_base = CMSPlugin(342 plugin_type='TextPlugin',343 placeholder=placeholder, 344 position=1, 345 language=settings.LANGUAGES[0][0]346 )347 plugin_base.insert_at(None, position='last-child', save=False)348 349 plugin = Text(body='')350 plugin_base.set_base_attr(plugin)351 plugin.save()352 self.assertEqual(CMSPlugin.objects.count(), 1)353 self.assertEqual(Text.objects.count(), 1)354 self.assertTrue(Placeholder.objects.count() > 0)355 page.delete()356 self.assertEqual(CMSPlugin.objects.count(), 0)357 self.assertEqual(Text.objects.count(), 0)358 self.assertEqual(Placeholder.objects.count(), 0)359 360 def test_get_page_from_request_on_non_cms_admin(self):361 request = self.get_request(362 reverse('admin:sampleapp_category_change', args=(1,))363 )364 page = get_page_from_request(request)365 self.assertEqual(page, None)366 367 def test_get_page_from_request_on_cms_admin(self):368 page = create_page("page", "nav_playground.html", "en")369 request = self.get_request(370 reverse('admin:cms_page_change', args=(page.pk,))371 )372 found_page = get_page_from_request(request)373 self.assertTrue(found_page)374 self.assertEqual(found_page.pk, page.pk)375 376 def test_get_page_from_request_on_cms_admin_nopage(self):377 request = self.get_request(378 reverse('admin:cms_page_change', args=(1,))379 )380 page = get_page_from_request(request)381 self.assertEqual(page, None)382 383 def test_get_page_from_request_cached(self):384 mock_page = 'hello world'385 request = self.get_request(386 reverse('admin:sampleapp_category_change', args=(1,))387 )388 request._current_page_cache = mock_page389 page = get_page_from_request(request)390 self.assertEqual(page, mock_page)391 392 def test_get_page_from_request_nopage(self):393 request = self.get_request('/')394 page = get_page_from_request(request)395 self.assertEqual(page, None)396 397 def test_get_page_from_request_with_page_404(self):398 page = create_page("page", "nav_playground.html", "en", published=True)399 page.publish()400 request = self.get_request('/does-not-exist/')401 found_page = get_page_from_request(request)402 self.assertEqual(found_page, None)403 404 def test_get_page_from_request_with_page_preview(self):405 page = create_page("page", "nav_playground.html", "en")406 request = self.get_request('%s?preview' % page.get_absolute_url())407 request.user.is_staff = False408 found_page = get_page_from_request(request)409 self.assertEqual(found_page, None)410 superuser = self.get_superuser()411 with self.login_user_context(superuser):412 request = self.get_request('%s?preview&draft' % page.get_absolute_url())413 found_page = get_page_from_request(request)414 self.assertTrue(found_page)415 self.assertEqual(found_page.pk, page.pk)416 417 def test_get_page_from_request_on_cms_admin_with_editplugin(self):418 page = create_page("page", "nav_playground.html", "en")419 request = self.get_request(420 reverse('admin:cms_page_change', args=(page.pk,)) + 'edit-plugin/42/'421 )422 found_page = get_page_from_request(request)423 self.assertTrue(found_page)424 self.assertEqual(found_page.pk, page.pk)425 426 def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):427 request = self.get_request(428 reverse('admin:cms_page_change', args=(1,)) + 'edit-plugin/42/'429 )430 page = get_page_from_request(request)431 self.assertEqual(page, None)432 433 def test_page_already_expired(self):434 """435 Test that a page which has a end date in the past gives a 404, not a436 500.437 """438 yesterday = datetime.date.today() - datetime.timedelta(days=1)439 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):440 page = create_page('page', 'nav_playground.html', 'en',441 publication_end_date=yesterday, published=True)442 resp = self.client.get(page.get_absolute_url('en'))443 self.assertEqual(resp.status_code, 404)444 445 def test_existing_overwrite_url(self):446 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):447 create_page('home', 'nav_playground.html', 'en', published=True)448 create_page('boo', 'nav_playground.html', 'en', published=True)449 data = {450 'title': 'foo',451 'overwrite_url': '/boo/',452 'slug': 'foo',453 'language': 'en',454 'template': 'nav_playground.html',455 'site': 1,456 }457 form = PageForm(data)458 self.assertFalse(form.is_valid())459 self.assertTrue('overwrite_url' in form.errors)460 461 def test_page_urls(self):462 page1 = create_page('test page 1', 'nav_playground.html', 'en',463 published=True)464 page2 = create_page('test page 2', 'nav_playground.html', 'en',465 published=True, parent=page1)466 page3 = create_page('test page 3', 'nav_playground.html', 'en',467 published=True, parent=page2)468 page4 = create_page('test page 4', 'nav_playground.html', 'en',469 published=True)470 page5 = create_page('test page 5', 'nav_playground.html', 'en',471 published=True, parent=page4)472 self.assertEqual(page1.get_absolute_url(),473 self.get_pages_root()+'')474 self.assertEqual(page2.get_absolute_url(),475 self.get_pages_root()+'test-page-2/')476 self.assertEqual(page3.get_absolute_url(),477 self.get_pages_root()+'test-page-2/test-page-3/')478 self.assertEqual(page4.get_absolute_url(),479 self.get_pages_root()+'test-page-4/')480 self.assertEqual(page5.get_absolute_url(),481 self.get_pages_root()+'test-page-4/test-page-5/')482 page3 = self.move_page(page3, page1)483 self.assertEqual(page3.get_absolute_url(),484 self.get_pages_root()+'test-page-3/')485 page5 = self.move_page(page5, page2)486 self.assertEqual(page5.get_absolute_url(),487 self.get_pages_root()+'test-page-2/test-page-5/')488 page3 = self.move_page(page3, page4)489 self.assertEqual(page3.get_absolute_url(),490 self.get_pages_root()+'test-page-4/test-page-3/')491 492 def test_home_slug_not_accessible(self):493 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):494 page = create_page('page', 'nav_playground.html', 'en', published=True)495 self.assertEqual(page.get_absolute_url('en'), '/')496 resp = self.client.get('/en/')497 self.assertEqual(resp.status_code, HttpResponse.status_code)498 resp = self.client.get('/en/page/')499 self.assertEqual(resp.status_code, HttpResponseNotFound.status_code)500 def test_public_home_page_replaced(self):501 """Test that publishing changes to the home page doesn't move the public version"""502 home = create_page('home', 'nav_playground.html', 'en', published = True, slug = 'home')503 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')504 home.publish()505 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')506 other = create_page('other', 'nav_playground.html', 'en', published = True, slug = 'other')507 other.publish()508 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')509 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')510 home = Page.objects.get(pk = home.id)511 home.in_navigation = True512 home.save()513 home.publish()514 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')515 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')516class NoAdminPageTests(CMSTestCase):517 urls = 'project.noadmin_urls'518 519 def setUp(self):520 admin = 'django.contrib.admin'521 noadmin_apps = [app for app in settings.INSTALLED_APPS if not app == admin]522 self._ctx = SettingsOverride(INSTALLED_APPS=noadmin_apps)523 self._ctx.__enter__()524 525 def tearDown(self):526 self._ctx.__exit__(None, None, None)527 528 def test_get_page_from_request_fakeadmin_nopage(self):529 request = self.get_request('/admin/')530 page = get_page_from_request(request)531 self.assertEqual(page, None)532class PreviousFilteredSiblingsTests(CMSTestCase):533 def test_with_publisher(self):534 home = create_page('home', 'nav_playground.html', 'en', published=True)535 home.publish()536 other = create_page('other', 'nav_playground.html', 'en', published=True)537 other.publish()538 other = Page.objects.get(pk=other.pk)539 home = Page.objects.get(pk=home.pk)540 self.assertEqual(other.get_previous_filtered_sibling(), home)541 self.assertEqual(home.get_previous_filtered_sibling(), None)542 543 def test_multisite(self):544 firstsite = Site.objects.create(name='first', domain='first.com')545 secondsite = Site.objects.create(name='second', domain='second.com')546 home = create_page('home', 'nav_playground.html', 'en', published=True, site=firstsite)547 home.publish()548 other = create_page('other', 'nav_playground.html', 'en', published=True, site=secondsite)549 other.publish()550 other = Page.objects.get(pk=other.pk)551 home = Page.objects.get(pk=home.pk)552 self.assertEqual(other.get_previous_filtered_sibling(), None)553 self.assertEqual(home.get_previous_filtered_sibling(), None)...

Full Screen

Full Screen

cms_tags.py

Source:cms_tags.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from classytags.arguments import Argument, MultiValueArgument3from classytags.core import Options, Tag4from classytags.helpers import InclusionTag5from classytags.parser import Parser6from cms.models import Page7from cms.plugin_rendering import render_plugins, render_placeholder8from cms.plugins.utils import get_plugins9from cms.utils import get_language_from_request10from cms.utils.moderator import get_cmsplugin_queryset, get_page_queryset11from cms.utils.placeholder import validate_placeholder_name12from django import template13from django.conf import settings14from django.contrib.sites.models import Site15from django.core.cache import cache16from django.core.mail import mail_managers17from django.utils.safestring import mark_safe18from django.utils.translation import ugettext_lazy as _19from itertools import chain20import re21register = template.Library()22def get_site_id(site):23 if site:24 if isinstance(site, Site):25 site_id = site.id26 elif isinstance(site, int) or (isinstance(site, basestring) and site.isdigit()):27 site_id = int(site)28 else:29 site_id = settings.SITE_ID30 else:31 site_id = settings.SITE_ID32 return site_id33def has_permission(page, request):34 return page.has_change_permission(request)35register.filter(has_permission)36CLEAN_KEY_PATTERN = re.compile(r'[^a-zA-Z0-9_-]')37def _clean_key(key):38 return CLEAN_KEY_PATTERN.sub('-', key)39def _get_cache_key(name, page_lookup, lang, site_id):40 if isinstance(page_lookup, Page):41 page_key = str(page_lookup.pk)42 else:43 page_key = str(page_lookup)44 page_key = _clean_key(page_key)45 return name+'__page_lookup:'+page_key+'_site:'+str(site_id)+'_lang:'+str(lang)46def _get_page_by_untyped_arg(page_lookup, request, site_id):47 """48 The `page_lookup` argument can be of any of the following types:49 - Integer: interpreted as `pk` of the desired page50 - String: interpreted as `reverse_id` of the desired page51 - `dict`: a dictionary containing keyword arguments to find the desired page52 (for instance: `{'pk': 1}`)53 - `Page`: you can also pass a Page object directly, in which case there will be no database lookup.54 - `None`: the current page will be used55 """56 if page_lookup is None:57 return request.current_page58 if isinstance(page_lookup, Page):59 return page_lookup60 if isinstance(page_lookup, basestring):61 page_lookup = {'reverse_id': page_lookup}62 elif isinstance(page_lookup, (int, long)):63 page_lookup = {'pk': page_lookup}64 elif not isinstance(page_lookup, dict):65 raise TypeError('The page_lookup argument can be either a Dictionary, Integer, Page, or String.')66 page_lookup.update({'site': site_id})67 try:68 return get_page_queryset(request).get(**page_lookup)69 except Page.DoesNotExist:70 site = Site.objects.get_current()71 subject = _('Page not found on %(domain)s') % {'domain':site.domain}72 body = _("A template tag couldn't find the page with lookup arguments `%(page_lookup)s\n`. "73 "The URL of the request was: http://%(host)s%(path)s") \74 % {'page_lookup': repr(page_lookup), 'host': site.domain, 'path': request.path}75 if settings.DEBUG:76 raise Page.DoesNotExist(body)77 else:78 if settings.SEND_BROKEN_LINK_EMAILS:79 mail_managers(subject, body, fail_silently=True)80 return None81class PageUrl(InclusionTag):82 template = 'cms/content.html'83 name = 'page_url'84 85 options = Options(86 Argument('page_lookup'),87 Argument('lang', required=False, default=None),88 Argument('site', required=False, default=None),89 )90 91 def get_context(self, context, page_lookup, lang, site):92 site_id = get_site_id(site)93 request = context.get('request', False)94 if not request:95 return {'content': ''}96 97 if request.current_page == "dummy":98 return {'content': ''}99 if lang is None:100 lang = get_language_from_request(request)101 cache_key = _get_cache_key('page_url', page_lookup, lang, site_id)+'_type:absolute_url'102 url = cache.get(cache_key)103 if not url:104 page = _get_page_by_untyped_arg(page_lookup, request, site_id)105 if page:106 url = page.get_absolute_url(language=lang)107 cache.set(cache_key, url, settings.CMS_CACHE_DURATIONS['content'])108 if url:109 return {'content': url}110 return {'content': ''}111register.tag(PageUrl)112register.tag('page_id_url', PageUrl)113def _get_placeholder(current_page, page, context, name):114 placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})115 if page.pk in placeholder_cache:116 return placeholder_cache[page.pk].get(name, None)117 placeholder_cache[page.pk] = {}118 placeholders = page.placeholders.all()119 for placeholder in placeholders:120 placeholder_cache[page.pk][placeholder.slot] = placeholder121 current_page._tmp_placeholders_cache = placeholder_cache122 return placeholder_cache[page.pk].get(name, None)123def get_placeholder_content(context, request, current_page, name, inherit):124 pages = [current_page]125 if inherit:126 pages = chain([current_page], current_page.get_cached_ancestors(ascending=True))127 for page in pages:128 placeholder = _get_placeholder(current_page, page, context, name)129 if placeholder is None:130 continue131 if not get_plugins(request, placeholder):132 continue133 content = render_placeholder(placeholder, context, name)134 if content:135 return content136 placeholder = _get_placeholder(current_page, current_page, context, name)137 return render_placeholder(placeholder, context, name)138class PlaceholderParser(Parser):139 def parse_blocks(self):140 for bit in getattr(self.kwargs['extra_bits'], 'value', self.kwargs['extra_bits']):141 if getattr(bit, 'value', bit.var.value) == 'or':142 return super(PlaceholderParser, self).parse_blocks()143 return144 145 146class PlaceholderOptions(Options):147 def get_parser_class(self):148 return PlaceholderParser149class Placeholder(Tag):150 """151 This template node is used to output page content and152 is also used in the admin to dynamically generate input fields.153 eg: {% placeholder "placeholder_name" %}154 {% placeholder "sidebar" inherit %}155 {% placeholder "footer" inherit or %}156 <a href="/about/">About us</a>157 {% endplaceholder %}158 Keyword arguments:159 name -- the name of the placeholder160 width -- additional width attribute (integer) which gets added to the plugin context161 (deprecated, use `{% with 320 as width %}{% placeholder "foo"}{% endwith %}`)162 inherit -- optional argument which if given will result in inheriting163 the content of the placeholder with the same name on parent pages164 or -- optional argument which if given will make the template tag a block165 tag whose content is shown if the placeholder is empty166 """167 name = 'placeholder'168 options = PlaceholderOptions(169 Argument('name', resolve=False),170 MultiValueArgument('extra_bits', required=False, resolve=False),171 blocks=[172 ('endplaceholder', 'nodelist'),173 ]174 )175 def render_tag(self, context, name, extra_bits, nodelist=None):176 validate_placeholder_name(name)177 width = None178 inherit = False179 for bit in extra_bits:180 if bit == 'inherit':181 inherit = True182 elif bit.isdigit():183 width = int(bit)184 import warnings185 warnings.warn(186 "The width parameter for the placeholder tag is deprecated.",187 DeprecationWarning188 )189 if not 'request' in context:190 return ''191 request = context['request']192 if width:193 context.update({'width': width})194 page = request.current_page195 if not page or page == 'dummy':196 return ''197 198 content = get_placeholder_content(context, request, page, name, inherit)199 if not content and nodelist:200 return nodelist.render(context)201 return content202 203 def get_name(self):204 return self.kwargs['name'].var.value.strip('"').strip("'")205register.tag(Placeholder)206class PageAttribute(Tag):207 """208 This template node is used to output attribute from a page such209 as its title or slug.210 Synopsis211 {% page_attribute "field-name" %}212 {% page_attribute "field-name" page_lookup %}213 Example214 {# Output current page's page_title attribute: #}215 {% page_attribute "page_title" %}216 {# Output page_title attribute of the page with reverse_id "the_page": #}217 {% page_attribute "page_title" "the_page" %}218 {# Output slug attribute of the page with pk 10: #}219 {% page_attribute "slug" 10 %}220 Keyword arguments:221 field-name -- the name of the field to output. Use one of:222 - title223 - menu_title224 - page_title225 - slug226 - meta_description227 - meta_keywords228 page_lookup -- lookup argument for Page, if omitted field-name of current page is returned.229 See _get_page_by_untyped_arg() for detailed information on the allowed types and their interpretation230 for the page_lookup argument.231 """232 name = 'page_attribute'233 options = Options(234 Argument('name', resolve=False),235 Argument('page_lookup', required=False, default=None)236 )237 238 valid_attributes = [239 "title",240 "slug",241 "meta_description",242 "meta_keywords",243 "page_title",244 "menu_title"245 ]246 247 def render_tag(self, context, name, page_lookup):248 if not 'request' in context:249 return ''250 name = name.lower()251 request = context['request']252 lang = get_language_from_request(request)253 page = _get_page_by_untyped_arg(page_lookup, request, get_site_id(None))254 if page == "dummy":255 return ''256 if page and name in self.valid_attributes:257 f = getattr(page, "get_%s" % name)258 return f(language=lang, fallback=True)259 return ''260register.tag(PageAttribute)261class CleanAdminListFilter(InclusionTag):262 template = 'admin/filter.html'263 name = 'clean_admin_list_filter'264 265 options = Options(266 Argument('cl'),267 Argument('spec'),268 )269 270 def get_context(self, context, cl, spec):271 choices = sorted(list(spec.choices(cl)), key=lambda k: k['query_string'])272 query_string = None273 unique_choices = []274 for choice in choices:275 if choice['query_string'] != query_string:276 unique_choices.append(choice)277 query_string = choice['query_string']278 return {'title': spec.title(), 'choices' : unique_choices}279def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None,280 site=None, cache_result=True):281 """282 Shows the content of a page with a placeholder name and given lookup283 arguments in the given language.284 This is useful if you want to have some more or less static content that is285 shared among many pages, such as a footer.286 See _get_page_by_untyped_arg() for detailed information on the allowed types287 and their interpretation for the page_lookup argument.288 """289 validate_placeholder_name(placeholder_name)290 291 request = context.get('request', False)292 site_id = get_site_id(site)293 if not request:294 return {'content': ''}295 if lang is None:296 lang = get_language_from_request(request)297 content = None298 if cache_result:299 cache_key = _get_cache_key('_show_placeholder_for_page', page_lookup, lang, site_id)+'_placeholder:'+placeholder_name300 content = cache.get(cache_key)301 if not content:302 page = _get_page_by_untyped_arg(page_lookup, request, site_id)303 if not page:304 return {'content': ''}305 try:306 placeholder = page.placeholders.get(slot=placeholder_name)307 except Placeholder.DoesNotExist:308 if settings.DEBUG:309 raise310 return {'content': ''}311 baseqs = get_cmsplugin_queryset(request)312 plugins = baseqs.filter(313 placeholder=placeholder,314 language=lang,315 placeholder__slot__iexact=placeholder_name,316 parent__isnull=True317 ).order_by('position').select_related()318 c = render_plugins(plugins, context, placeholder)319 content = "".join(c)320 if cache_result:321 cache.set(cache_key, content, settings.CMS_CACHE_DURATIONS['content'])322 if content:323 return {'content': mark_safe(content)}324 return {'content': ''}325class ShowPlaceholderById(InclusionTag):326 template = 'cms/content.html'327 name = 'show_placeholder_by_id'328 329 options = Options(330 Argument('placeholder_name'),331 Argument('reverse_id'),332 Argument('lang', required=False, default=None),333 Argument('site', required=False, default=None),334 )335 336 def get_context(self, *args, **kwargs):337 return _show_placeholder_for_page(**self.get_kwargs(*args, **kwargs))338 339 def get_kwargs(self, context, placeholder_name, reverse_id, lang, site):340 return {341 'context': context,342 'placeholder_name': placeholder_name,343 'page_lookup': reverse_id,344 'lang': lang,345 'site': site346 }347register.tag(ShowPlaceholderById)348register.tag('show_placeholder', ShowPlaceholderById)349class ShowUncachedPlaceholderById(ShowPlaceholderById):350 name = 'show_uncached_placeholder_by_id'351 def get_kwargs(self, *args, **kwargs):352 kwargs = super(ShowUncachedPlaceholderById, self).get_kwargs(*args, **kwargs)353 kwargs['cache_result'] = False354 return kwargs355register.tag(ShowUncachedPlaceholderById)356register.tag('show_uncached_placeholder', ShowUncachedPlaceholderById)357class CMSToolbar(InclusionTag):358 template = 'cms/toolbar/toolbar.html'359 name = 'cms_toolbar'360 361 def render(self, context):362 request = context.get('request', None)363 if not request:364 return ''365 toolbar = getattr(request, 'toolbar', None)366 if not toolbar:367 return ''368 if not toolbar.show_toolbar:369 return ''370 return super(CMSToolbar, self).render(context)371 372 def get_context(self, context):373 context['CMS_TOOLBAR_CONFIG'] = context['request'].toolbar.as_json(context)374 return context...

Full Screen

Full Screen

moderator.py

Source:moderator.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import datetime3from django.utils.translation import ugettext as _4from django.conf import settings5from cms.models import Page, PageModeratorState, PageModerator, CMSPlugin, Title6I_APPROVE = 100 # current user should approve page7I_APPROVE_DELETE = 2008def page_changed(page, old_page=None, force_moderation_action=None):9 """Called from page post save signal. If page already had pk, old version10 of page is provided in old_page argument.11 """12 # get user from thread locals13 from cms.utils.permissions import get_current_user14 user = get_current_user()15 force_moderation_action = force_moderation_action or getattr(page, 'force_moderation_action', None)16 if force_moderation_action:17 PageModeratorState(user=user, page=page, action=force_moderation_action).save()18 return19 if not old_page:20 # just newly created page21 PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_ADD).save()22 if (old_page is None and page.published) or \23 (old_page and not old_page.published == page.published):24 action = page.published and PageModeratorState.ACTION_PUBLISH or PageModeratorState.ACTION_UNPUBLISH25 PageModeratorState(user=user, page=page, action=action).save()26 if ((old_page and not old_page.moderator_state == page.moderator_state) or not old_page) \27 and page.requires_approvement():28 # update_moderation_message can be called after this :S -> recipient will not29 # see the last message30 mail_approvement_request(page, user)31 # TODO: if page was changed, remove all approvements from higher instances,32 # but keep approvements by lower instances, if there are any33def update_moderation_message(page, message):34 """This is bit special.. It updates last page state made from current user35 for given page. Its called after page is saved - page state is created when36 page gets saved (in signal), so this might have a concurrency issue, but 37 probably will work in 99,999%.38 39 If any page state is'nt found in last UPDATE_TOLERANCE seconds, a new state40 will be created instead of affecting old message. 41 """42 UPDATE_TOLERANCE = 30 # max in last 30 seconds43 from cms.utils.permissions import get_current_user44 user = get_current_user()45 created = datetime.datetime.now() - datetime.timedelta(seconds=UPDATE_TOLERANCE)46 try:47 state = page.pagemoderatorstate_set.filter(user=user, created__gt=created).order_by('-created')[0]48 # just state without message!!49 assert not state.message 50 except (IndexError, AssertionError):51 state = PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_CHANGED)52 state.message = message53 state.save()54def page_moderator_state(request, page):55 """Return moderator page state from page.moderator_state, but also takes 56 look if current user is in the approvement path, and should approve the this 57 page. In this case return 100 as an state value. 58 59 Returns:60 dict(state=state, label=label)61 """62 state, label = page.moderator_state, ""63 under_moderation = page.get_moderator_queryset()64 # TODO: OPTIMIZE!! calls 1 or 2 q per list item (page)65 if settings.CMS_MODERATOR:66 if state == Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS:67 label = _('parent first')68 elif page.requires_approvement() and page.has_moderate_permission(request) \69 and under_moderation.filter(user=request.user).count() \70 and not page.pagemoderatorstate_set.filter(user=request.user, action=PageModeratorState.ACTION_APPROVE).count():71 # only if he didn't approve already...72 is_delete = state == Page.MODERATOR_NEED_DELETE_APPROVEMENT73 state = is_delete and I_APPROVE_DELETE or I_APPROVE 74 label = is_delete and _('delete') or _('approve')75 elif not page.is_approved():76 # if no moderator, we have just 2 states => changed / unchanged77 state = Page.MODERATOR_NEED_APPROVEMENT78 if not page.is_approved() and not label:79 if under_moderation.count():80 label = dict(page.moderator_state_choices)[state] 81 return dict(state=state, label=label)82def moderator_should_approve(request, page):83 """Says if user should approve given page. (just helper)84 """85 return page_moderator_state(request, page)['state'] >= I_APPROVE86def requires_moderation(page):87 """Returns True if page requires moderation88 """89 return bool(page.get_moderator_queryset().count())90def will_require_moderation(target_id, position):91 """Check if newly added page will require moderation92 """93 if not settings.CMS_MODERATOR:94 return False95 target = Page.objects.get(pk=target_id)96 if position == 'first-child':97 return requires_moderation(target)98 elif position in ('left', 'right'):99 if target.parent:100 return requires_moderation(target.parent)101 return False102def get_test_moderation_level(page, user=None, include_user=True):103 """Returns min moderation level for page, and result of user test if 104 user is given, so output is always tuple of:105 106 (moderation_level, requires_approvement)107 108 Meaning of requires_approvement is - somebody of higher instance must 109 approve changes made on this page by given user. 110 111 NOTE: May require some optimization, might call 3 huge sql queries in 112 worse case113 """114 qs = page.get_moderator_queryset()115 if not settings.CMS_MODERATOR or (user and user.is_superuser):116 if include_user and qs.filter(user__id=user.id, moderate_page=True).count():117 return 0, True118 return 0, False119 if qs.filter(user__is_superuser=True).count():120 return 0, True121 if user:122 if qs.filter(user__id=user.id, user__globalpagepermission__gt=0).count():123 return 0, False124 try:125 moderator = qs.filter(user__id=user.id).select_related()[0]126 return moderator.page.level, False127 except IndexError:128 pass129 else:130 if qs.filter(user__globalpagepermission__gt=0).count():131 return 0, True132 try:133 moderator = qs.select_related()[0]134 except IndexError:135 return PageModerator.MAX_MODERATION_LEVEL, False136 return moderator.page.level, True137def approve_page(request, page):138 """Main approving function. Two things can happen here, depending on user139 level:140 141 1.) User is somewhere in the approvement path, but not on the top. In this142 case just mark this page as approved by this user.143 144 2.) User is on top of approvement path. Draft page with all dependencies 145 will be `copied` to public model, page states log will be cleaned. 146 147 """148 moderation_level, moderation_required = get_test_moderation_level(page, request.user, False)149 if not moderator_should_approve(request, page):150 # escape soon if there isn't any approval required by this user151 if not page.publisher_public or page.get_absolute_url() != page.publisher_public.get_absolute_url():152 page.publish()153 else:154 return155 if not moderation_required:156 # this is a second case - user can publish changes157 if page.pagemoderatorstate_set.get_delete_actions().count():158 # it is a delete request for this page!!159 page.delete_with_public()160 else:161 page.publish()162 else:163 # first case - just mark page as approved from this user164 PageModeratorState(user=request.user, page=page, action=PageModeratorState.ACTION_APPROVE).save()165 page.save(change_state=False)166def get_model_queryset(model, request=None):167 """Decision function used in frontend - says which model should be used.168 Public models are used only if CMS_MODERATOR.169 """170 if not settings.CMS_MODERATOR:171 # We do not use moderator172 return model.objects.drafts()173 # We do use moderator174 if request:175 preview_draft = ('preview' in request.GET and 'draft' in request.GET)176 edit_mode = ('edit' in request.GET or request.session.get('cms_edit', False))177 if preview_draft or edit_mode: 178 return model.objects.drafts()179 # Default case / moderator is used but there is no request180 return model.objects.public()181# queryset helpers for basic models182get_page_queryset = lambda request=None: get_model_queryset(Page, request) 183get_title_queryset = lambda request=None: Title.objects.all() # not sure if we need to only grab public items here184get_cmsplugin_queryset = lambda request=None: CMSPlugin.objects.all() # CMSPlugin is no longer extending from Publisher185def mail_approvement_request(page, user=None):186 """Sends approvement request over email to all users which should approve187 this page if they have an email entered.188 189 Don't send it to current user - he should know about it, because he made the190 change.191 """192 if not settings.CMS_MODERATOR or not page.requires_approvement():193 return194 recipient_list = []195 for moderator in page.get_moderator_queryset():196 email = moderator.user.email197 if email and not email in recipient_list:198 recipient_list.append(email)199 if user and user.email in recipient_list:200 recipient_list.remove(user.email)201 if not recipient_list:202 return203 from django.contrib import admin204 from django.contrib.sites.models import Site205 from cms.utils.urlutils import urljoin206 from cms.utils.mail import send_mail207 site = Site.objects.get_current()208 subject = _('CMS - Page %s requires approvement.') % unicode(page)209 context = {210 'page': page,211 'admin_url': "http://%s" % urljoin(site.domain, admin.site.root_path, 'cms/page', page.id),212 }...

Full Screen

Full Screen

test_page_retrieval.py

Source:test_page_retrieval.py Github

copy

Full Screen

...4from mypage.pages.models import Page5from mypage.pages.views import get_page6from unit_project.helpers import create_filled_default_page, SessionWrapper7from unit_project import template_loader8class TestGetPage(DatabaseTestCase):9 def setUp(self):10 super(TestGetPage, self).setUp()11 template_loader.templates = {12 'widgets.widget/widget.html': '',13 'testwidgets.testwidget/widget-a/widget.html' : '',14 'testwidgets.testwidget/widget.html' : '',15 }16 create_filled_default_page(self)17 self.user = User.objects.create()18 self.anonymous_user = AnonymousUser()19 self.default_page = Page.objects.get_for_id(settings.DEFAULT_PAGE_ID)20 def get_session(self, key=u'123', session_dict=None):21 session = SessionWrapper(session_dict or {})22 session.session_key = key...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1from django.conf import settings2from django import http3from mypage.pages.models import Page, UserPage, SessionPage4from mypage.pages.layout import Layout5from mypage.widgets.models import get_object6from django.db.models import ObjectDoesNotExist7from mypage.pages.migrations.utils.layout_refactor_migration import migrate_page 8def get_page(user, session, for_update=False, defaults=None, from_page=None):9 """10 Get page for the current user. Check if they have a UserPage11 and if so, return it, return the default page otherwise.12 If for_update is specified, only return the defaul page for users13 that can edit Page (has_perm('change_page')) so that regular users won't override14 """15 from_page = from_page or settings.DEFAULT_PAGE_ID16 page = None17 session_page = None18 if for_update:19 session.modified = True20 defaults = defaults or session.get('defaults', {})21 try:22 session_page = SessionPage.objects.get(session_key=session.session_key)23 except SessionPage.DoesNotExist, e:24 pass25 if user.is_authenticated():26 # Authenticated users27 try:28 page = UserPage.objects.get(user=user)29 except UserPage.DoesNotExist, e:30 if session_page:31 # user has a session_page, clone it and save it32 page = UserPage.objects.clone_from_page(33 page=session_page,34 defaults=defaults,35 user=user,36 )37 # delete the now obsolete session_page38 session_page.delete()39 session_page = None40 elif for_update:41 # create user page from default42 page = UserPage.objects.clone_from_page(43 page=Page.objects.get_for_id(from_page),44 defaults=defaults,45 user=user46 )47 else:48 # anonymous user49 if session_page:50 # user already as a session page51 page = session_page52 elif for_update:53 # Unknown user without UserPage or SessionPage wanting to edit page must clone SessionPage54 page = SessionPage.objects.clone_from_page(55 page=Page.objects.get_for_id(from_page),56 defaults=defaults,57 session_key=session.session_key58 )59 if not page:60 # read only page61 page = Page.objects.get_for_id(from_page)62 if defaults:63 for k, v in defaults.items():64 setattr(page, k, v)65 if not page.layout_migrated:66 page = migrate_page(page)67 return page68def get_widget_or_404(page, content_type_id, object_id):69 """70 Return a widget using the ct_id and obj_id pair71 """72 try:73 widget = get_object(content_type_id, object_id)74 except ObjectDoesNotExist, e:75 raise http.Http40476 try:77 wil = page.layout.get_widget(int(content_type_id), int(object_id))78 except Layout.WidgetInLayoutDoesNotExist, e:79 raise http.Http40480 return widget, wil81def is_custom_page(page):82 """83 Custom pages could be updated/deleted by users84 """...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

1#from pages.models import Page2from apps.carosel.models import Carosel3from django.shortcuts import render_to_response4from django.template import RequestContext5#from news.models import Article6#from blog.models import Post7#from mediaviewer.models import *8def Home(request, slug):9# page_items = Page.objects.get(slug='home')10# page_contents = page_items.pagecontent_set.all().order_by('position')11 carosel_list = Carosel.objects.all()[:3]12 13# farticle_list = Article.objects.filter(featured=True).order_by('-created')14# farticle = farticle_list[0]15 16# fimage_list = Image.objects.filter(featured=True).order_by('-created')17 # fimage = fimage_list[0]18# posts = Post.objects.all().order_by('-created')[:8]19# return render_to_response('layouts/home.html', {'page':page_items, 'page_contents':page_contents, 'carosel_list': carosel_list, 'farticle':farticle, 'posts':posts, 'fimage':fimage},context_instance = RequestContext(request))20 return render_to_response('index.html', {'carosel_list': carosel_list})21'''22def About(request):23 page_items = Page.objects.get(slug='about')24 page_contents = page_items.pagecontent_set.all().order_by('position')25 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})26def Work(request):27 page_items = Page.objects.get(slug='work')28 page_contents = page_items.pagecontent_set.all().order_by('position')29 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})30def Media(request):31 page_items = Page.objects.get(slug='media')32 page_contents = page_items.pagecontent_set.all().order_by('position')33 return render_to_response('about.html',{'page':page_items, 'page_contents':page_contents})34def Archives(request):35 page_items = Page.objects.get(slug='archives')36 page_contents = page_items.pagecontent_set.all().order_by('position')37 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})38def Contact(request):39 page_items = Page.objects.get(slug='contact')40 page_contents = page_items.pagecontent_set.all().order_by('position')41 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})42def GetInvolved(request):43 page_items = Page.objects.get(slug='get-involved')44 page_contents = page_items.pagecontent_set.all().order_by('position')45 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { Button, Welcome } from '@storybook/react/demo';6import { Page } from 'storybook-root';7import './storybook-root.css';8storiesOf('Page', module)9 .add('Page', () => <Page />);10import { configure } from '@storybook/react';11import './storybook-root.css';12function loadStories() {13 require('../test');14}15configure(loadStories, module);16module.exports = ({ config }) => {17 config.module.rules.push({18 include: path.resolve(__dirname, '../'),19 });20 return config;21};22@import "~storybook-root/lib/index.css";23import React from 'react';24import { storiesOf } from '@storybook/react';25import { action } from '@storybook/addon-actions';26import { linkTo } from '@storybook/addon-links';27import { Button, Welcome } from '@storybook/react/demo';28import { Page } from 'storybook-root';29import './storybook-root.css';30storiesOf('Page', module)31 .add('Page', () => <Page />);32import { configure } from '@storybook/react';33import './storybook-root.css';34function loadStories() {35 require('../test');36}37configure(loadStories, module);38module.exports = ({ config }) => {39 config.module.rules.push({40 include: path.resolve(__dirname, '../'),41 });42 return config;43};44@import "~storybook-root/lib/index.css";45import React from 'react';46import { storiesOf } from '@storybook/react';47import { action } from '@storybook/addon-actions';48import { linkTo } from '@storybook/addon-links';49import {

Full Screen

Using AI Code Generation

copy

Full Screen

1const Page = require('storybook-root').Page;2const Page = require('storybook-root').Page;3const Page = require('storybook-root').Page;4const Page = require('storybook-root').Page;5const Page = require('storybook-root').Page;6const Page = require('storybook-root').Page;7const Page = require('storybook-root').Page;8const Page = require('storybook-root').Page;9const Page = require('storybook-root').Page;10const Page = require('storybook-root').Page;11const Page = require('storybook-root').Page;12const Page = require('storybook-root').Page;13const Page = require('storybook-root').Page;14const Page = require('storybook-root').Page;15const Page = require('storybook-root').Page;16const Page = require('storybook-root').Page;17const Page = require('storybook-root').Page;18const Page = require('storybook-root').Page;19const Page = require('storybook-root').Page;20const Page = require('storybook-root').Page;21const Page = require('storybook-root').Page;22const Page = require('storybook-root').Page;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Page } from 'storybook-root'2export default function Test() {3 return (4}5import { PageComponent } from 'storybook-root'6export default function Page({ children }) {7 return (8 {children}9}10import { Page } from 'storybook-root'11export default function Test() {12 return (13}14import { PageComponent } from 'storybook-root'15export default function Page({ children }) {16 return (17 {children}18}19import { Page } from 'storybook-root'20export default function Test() {21 return (22}23import { PageComponent } from '../'24export default function Page({ children }) {25 return (26 {children}27}28import { Page } from 'storybook-root'29export default function Test() {30 return (31}32import { PageComponent } from '../'33export default function Page({ children

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Page } from 'storybook-root';2const page = new Page();3page.setPageTitle('My Page Title');4page.setPageDescription('My Page Description');5page.setPageKeywords('My Page Keywords');6page.setPageImage('My Page Image');7page.setPageUrl('My Page Url');8page.setPageType('My Page Type');9page.setPageSiteName('My Page Site Name');10page.setPageLocale('My Page Locale');11page.setPageLocaleAlternate('My Page Locale Alternate');12page.setPageFacebookAppId('My Page Facebook App Id');13page.setPageFacebookAdmins('My Page Facebook Admins');14page.setPageTwitterSite('My Page Twitter Site');15page.setPageTwitterCreator('My Page Twitter Creator');16page.setPageTwitterCard('My Page Twitter Card');17page.setPageTwitterTitle('My Page Twitter Title');18page.setPageTwitterDescription('My Page Twitter Description');19page.setPageTwitterImage('My Page Twitter Image');20page.setPageTwitterImageAlt('My Page Twitter Image Alt');21page.setPageTwitterPlayer('My Page Twitter Player');22page.setPageTwitterPlayerStream('My Page Twitter Player Stream');23page.setPageTwitterPlayerWidth('My Page Twitter Player Width');24page.setPageTwitterPlayerHeight('My Page Twitter Player Height');25page.setPageTwitterPlayerStreamContentType('My Page Twitter Player Stream Content Type');26page.setPageTwitterPlayerStreamUrl('My Page Twitter Player Stream Url');27page.setPageTwitterPlayerStreamWidth('My Page Twitter Player Stream Width');28page.setPageTwitterPlayerStreamHeight('My Page Twitter Player Stream Height');29page.setPageTwitterPlayerStreamLabel('My Page Twitter Player Stream Label');30page.setPageOgTitle('My Page Og Title');31page.setPageOgDescription('My Page Og Description');32page.setPageOgImage('My Page Og Image');33page.setPageOgImageWidth('My Page Og Image Width');34page.setPageOgImageHeight('My Page Og Image Height');35page.setPageOgImageAlt('My Page Og Image Alt');36page.setPageOgType('My Page Og Type');37page.setPageOgUrl('My Page Og Url');38page.setPageOgAudio('My Page Og Audio');39page.setPageOgAudioType('My Page Og Audio Type');40page.setPageOgVideo('My Page Og Video');41page.setPageOgVideoType('My Page Og Video Type');42page.setPageOgVideoWidth('My Page Og Video Width');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Page } from 'storybook-root'2export default ({ name }) => <Page>{name}</Page>3import { storiesOf } from '@storybook/react'4import MyComponent from './MyComponent'5storiesOf('MyComponent').add('default', () => (6import { render } from 'react-testing-library'7import MyComponent from './MyComponent'8test('MyComponent renders', () => {9 const { getByText } = render(<MyComponent name="MyComponent" />)10 expect(getByText('MyComponent')).toBeInTheDocument()11})12import { mount } from 'enzyme'13import MyComponent from './MyComponent'14test('MyComponent renders', () => {15 const wrapper = mount(<MyComponent name="MyComponent" />)16 expect(wrapper.text()).toContain('MyComponent')17})18describe('MyComponent', () => {19 it('renders', () => {20 cy.visitStorybook()21 cy.loadStory('MyComponent', 'default')22 cy.get('body').should('contain', 'MyComponent')23 })24})25import { Meta, Preview, Story } from '@storybook/addon-docs/blocks'26import MyComponent from './MyComponent'27import MyComponent from './MyComponent'28import MyComponent from './MyComponent'29import MyComponent from './MyComponent'30import MyComponent from './MyComponent'31import MyComponent from

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import Story from './Story';5storiesOf('Page', module)6 .add('Page 1', () => <Story title="Page 1" />)7 .add('Page 2', () => <Story title="Page 2" />)8 .add('Page 3', () => <Story title="Page 3" />);9import React from 'react';10import { Page } from 'storybook-root';11export default ({ title }) => (12 <Page title={title}>13);14import React from 'react';15import { storiesOf } from '@storybook/react';16import { action } from '@storybook/addon-actions';17export const Page = ({ title, children }) => (18 <h1>{title}</h1>19 {children}20);21export * from './Page';22import React from 'react';23export const Page = ({ title, children }) => (24 <h1>{title}</h1>25 {children}26);27I have a project that has a storybook-root directory with a Page component that I want to use in my stories. I want to be able to use the Page component in my stories by importing it from storybook-root. I also want to be able to test the Page component outside of storybook by importing it from storybook-root. However, when I run the storybook command, I get the following error: Module not found: Error: Can't resolve 'storybook-root' in 'C:\Users\james\Documents\Projects\storybook-root\test'.I have tried a couple of different approaches, but I am still getting the same error. Here is what I have tried:If I run the storybook command, I get the following error: Module not found: Error: Can't resolve 'storybook-root' in 'C:\Users\james\Documents\Projects\storybook-root\test'.I have tried a couple of different approaches, but I am still getting the same error. Here is what I have tried:If I run

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Page } from 'storybook-root';2Page.setPageName('pageName');3Page.setPageName('pageName', 'subPageName');4Page.setPageName('pageName', 'subPageName', 'subSubPageName');5Page.setPageName('pageName');6Page.setPageName('pageName', 'subPageName');7Page.setPageName('pageName', 'subPageName', 'subSubPageName');8Page.setPageName('pageName');9Page.setPageName('pageName', 'subPageName');10Page.setPageName('pageName', 'subPageName', 'subSubPageName');11Page.setPageName('pageName');12Page.setPageName('pageName', 'subPageName');13Page.setPageName('pageName', 'subPageName', 'subSubPageName');14Page.setPageName('pageName');15Page.setPageName('pageName', 'subPageName');16Page.setPageName('pageName', 'subPageName', 'subSubPageName');17Page.setPageName('pageName');18Page.setPageName('pageName', 'subPageName');19Page.setPageName('pageName', 'subPageName', 'subSubPageName');20Page.setPageName('pageName');21Page.setPageName('pageName', 'subPageName');22Page.setPageName('pageName', 'subPageName', 'subSubPageName');23Page.setPageName('pageName');24Page.setPageName('pageName', 'subPageName');25Page.setPageName('pageName', 'subPageName', 'subSubPageName');26Page.setPageName('pageName');27Page.setPageName('pageName', 'subPageName');28Page.setPageName('pageName', 'subPageName', 'subSubPageName');29Page.setPageName('pageName');30Page.setPageName('pageName', 'subPageName

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Page } from 'storybook-root';2import { Page } from 'storybook-root';3export { Page };4import { Page } from 'storybook-root';5import { Page } from 'storybook-root';6export { Page as default };7import Page from 'storybook-root';8import Page from 'storybook-root';9export default { Page };10import { Page } from 'storybook-root';11import { Page } from 'storybook-root';12export default { Page };13import { Page } from 'storybook-root';14import { Page } from 'storybook-root';15export default { Page };16import { Page } from

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful