def test_toolbar_switch_urls(self): user = self.get_superuser() user_settings = UserSettings(language="en", user=user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() page = create_page("page", "nav_playground.html", "en", published=True) create_title("fr", "french home", page) publish_page(page, user, "fr") with self.login_user_context(user): response = self.client.get( "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) self.assertContains( response, "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF'), 1, 200) response = self.client.get( "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')) self.assertContains( response, "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'), 1, 200)
def test_05_remove_plugin_not_associated_to_page(self): """ Test case for PlaceholderField """ page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) ph = Placeholder(slot="subplugin") ph.save() plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder': ph.pk, 'parent': int(response.content) } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) # no longer allowed for security reasons self.assertEqual(response.status_code, 404)
def __init__(self, request): super(CMSToolbar, self).__init__() self.left_items = None self.right_items = None self.menus = {} self.request = request self.login_form = CMSToolbarLoginForm(request=request) self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False) self.build_mode = self.is_staff and self.request.session.get('cms_build', False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False) if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language if self.is_staff: try: user_settings = UserSettings.objects.get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() self.toolbar_language = user_settings.language self.clipboard = user_settings.clipboard
def fill_placeholder(self, placeholder=None): if placeholder is None: placeholder = Placeholder(slot=u"some_slot") placeholder.save() # a good idea, if not strictly necessary # plugin in placeholder plugin_1 = add_plugin( placeholder, u"TextPlugin", u"en", body=u"01", ) plugin_1.save() # IMPORTANT: plugins must be reloaded, before they can be assigned # as a parent. Otherwise, the MPTT structure doesn't seem to rebuild # properly. # child of plugin_1 plugin_2 = add_plugin( placeholder, u"TextPlugin", u"en", body=u"02", ) plugin_1 = self.reload(plugin_1) plugin_2.parent = plugin_1 plugin_2.save() return placeholder
def test_05_remove_plugin_not_associated_to_page(self): """ Test case for PlaceholderField """ page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { "plugin_type": "TextPlugin", "language": settings.LANGUAGES[0][0], "placeholder": page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) ph = Placeholder(slot="subplugin") ph.save() plugin_data = { "plugin_type": "TextPlugin", "language": settings.LANGUAGES[0][0], "placeholder": ph.pk, "parent": int(response.content), } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) plugin_data = {"plugin_id": int(response.content)} response = response.client.post(URL_CMS_PLUGIN_REMOVE, plugin_data) self.assertEquals(response.status_code, 200)
def __init__(self, request): super(CMSToolbar, self).__init__() self.right_items = [] self.left_items = [] self.populated = False self.post_template_populated = False self.menus = {} self.request = request self.login_form = CMSToolbarLoginForm(request=request) self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get("cms_edit", False) self.edit_mode_url_on = get_cms_setting("CMS_TOOLBAR_URL__EDIT_ON") self.edit_mode_url_off = get_cms_setting("CMS_TOOLBAR_URL__EDIT_OFF") self.build_mode = self.is_staff and self.request.session.get("cms_build", False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get("cms_edit", False) self.obj = None self.redirect_url = None if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language if self.is_staff: try: user_settings = UserSettings.objects.select_related("clipboard").get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or ( not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE ): self.toolbar_language = user_settings.language else: user_settings.language = self.language user_settings.save() self.clipboard = user_settings.clipboard with force_language(self.language): try: self.app_name = resolve(self.request.path).app_name except Resolver404: self.app_name = "" toolbars = toolbar_pool.get_toolbars() self.toolbars = SortedDict() app_key = "" for key in toolbars: app_name = ".".join(key.split(".")[:-2]) if app_name == self.app_name and len(key) > len(app_key): app_key = key for key in toolbars: toolbar = toolbars[key](self.request, self, key == app_key, app_key) self.toolbars[key] = toolbar
def __init__(self, request): super(CMSToolbar, self).__init__() self.right_items = [] self.left_items = [] self.populated = False self.post_template_populated = False self.menus = {} self.request = request self.login_form = CMSToolbarLoginForm(request=request) self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False) self.edit_mode_url_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') self.edit_mode_url_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') self.build_mode = self.is_staff and self.request.session.get('cms_build', False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False) self.obj = None self.redirect_url = None if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language if self.is_staff: try: user_settings = UserSettings.objects.select_related('clipboard').get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or ( not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE): self.toolbar_language = user_settings.language else: user_settings.language = self.language user_settings.save() self.clipboard = user_settings.clipboard with force_language(self.language): try: self.app_name = resolve(self.request.path).app_name except Resolver404: self.app_name = "" toolbars = toolbar_pool.get_toolbars() self.toolbars = SortedDict() app_key = '' for key in toolbars: app_name = ".".join(key.split(".")[:-2]) if app_name == self.app_name and len(key) > len(app_key): app_key = key for key in toolbars: toolbar = toolbars[key](self.request, self, key == app_key, app_key) self.toolbars[key] = toolbar
def get_user_settings(self): user_settings = None if self.is_staff: try: user_settings = UserSettings.objects.select_related("clipboard").get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() return user_settings
def get_user_settings(self): user_settings = None if self.is_staff: try: user_settings = UserSettings.objects.select_related('clipboard').get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() return user_settings
def test_toolbar_switch_urls(self): user = self.get_superuser() user_settings = UserSettings(language="en", user=user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() page = create_page("page", "nav_playground.html", "en", published=True) create_title("fr", "french home", page) publish_page(page, user, "fr") page.set_as_homepage() edit_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') edit_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') with self.login_user_context(user): response = self.client.get("/fr/?{}".format(edit_on)) expected = """ <a href="?structure" class="cms-btn cms-btn-disabled" title="Toggle structure" data-cms-structure-btn='{ "url": "/fr/?structure", "name": "Structure" }' data-cms-content-btn='{ "url": "/fr/?edit", "name": "Content" }'> <span class="cms-icon cms-icon-plugins"></span></a> """ self.assertContains( response, expected, count=1, html=True, ) self.assertContains( response, '<a class="cms-btn cms-btn-switch-save" href="/fr/?preview&{}">' '<span>View published</span></a>'.format(edit_off), count=1, html=True, ) response = self.client.get("/fr/?preview&{}".format(edit_off)) self.assertContains( response, expected, count=1, html=True, ) self.assertContains( response, '<a class="cms-btn cms-btn-action cms-btn-switch-edit" href="/fr/?{}">Edit</a>' .format(edit_on), count=1, html=True, )
def test_toolbar_switch_urls(self): user = self.get_superuser() user_settings = UserSettings(language="en", user=user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() page = create_page("page", "nav_playground.html", "en", published=True) create_title("fr", "french home", page) publish_page(page, user, "fr") with self.login_user_context(user): response = self.client.get("/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) self.assertContains(response, "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF'), 1, 200) response = self.client.get("/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')) self.assertContains(response, "/fr/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'), 1, 200)
def test_in_placeholders(self): plugin = add_plugin( self.page.placeholders.get(slot='content'), 'LinkPlugin', 'en', internal_link=self.page, ) self.assertEqual(plugin.get_link(), '/en/content/') placeholder = Placeholder(slot="generated_placeholder") placeholder.save() plugin = add_plugin( placeholder, 'LinkPlugin', 'en', internal_link=self.static_page, ) # the generated placeholder has no page attached to it, thus: self.assertEqual(plugin.get_link(), '//example.com/en/static-content/') static_placeholder = StaticPlaceholder.objects.create( name='content_static', code='content_static', site_id=1, ) static_placeholder.save() plugin_a = add_plugin( static_placeholder.draft, 'LinkPlugin', 'en', internal_link=self.page, ) plugin_b = add_plugin( static_placeholder.public, 'LinkPlugin', 'en', internal_link=self.static_page, ) # static placeholders will always return the full path self.assertEqual(plugin_a.get_link(), '//example.com/en/content/') self.assertEqual(plugin_b.get_link(), '//example.com/en/static-content/')
def test_render_placeholder_toolbar(self): placeholder = Placeholder() placeholder.slot = "test" placeholder.pk = placeholder.id = 99 context = SekizaiContext() context["request"] = AttributeObject( REQUEST={"language": "en"}, GET=[], session={}, path="/", user=self.test_user, current_page=None, method="GET", ) classes = ["cms_placeholder-%s" % placeholder.pk, "cms_placeholder"] output = render_placeholder_toolbar(placeholder, context, "test", "en") for cls in classes: self.assertTrue(cls in output, "%r is not in %r" % (cls, output))
def fill_placeholder(self, placeholder=None): if placeholder is None: placeholder = Placeholder(slot=u"some_slot") placeholder.save() # a good idea, if not strictly necessary # plugin in placeholder plugin_1 = add_plugin(placeholder, u"TextPlugin", u"en", body=u"01") plugin_1.save() # IMPORTANT: plugins must be reloaded, before they can be assigned # as a parent. Otherwise, the MPTT structure doesn't seem to rebuild # properly. # child of plugin_1 plugin_2 = add_plugin(placeholder, u"TextPlugin", u"en", body=u"02") plugin_1 = self.reload(plugin_1) plugin_2.parent = plugin_1 plugin_2.save() return placeholder
def test_render_placeholder_toolbar(self): placeholder = Placeholder() placeholder.slot = 'test' placeholder.pk = placeholder.id = 99 with self.login_user_context(self.get_superuser()): request = self.get_request(page=None) request.session = {'cms_edit': True} request.toolbar = CMSToolbar(request) renderer = self.get_content_renderer(request) context = SekizaiContext() context['request'] = request classes = [ "cms-placeholder-%s" % placeholder.pk, 'cms-placeholder', ] output = renderer.render_placeholder(placeholder, context, 'en', editable=True) for cls in classes: self.assertTrue(cls in output, '%r is not in %r' % (cls, output))
def test_render_placeholder_toolbar(self): placeholder = Placeholder() placeholder.slot = 'test' placeholder.pk = placeholder.id = 99 context = SekizaiContext() context['request'] = AttributeObject( REQUEST={'language': 'en'}, GET=[], session={}, path='/', user=self.test_user, current_page=None, method='GET', ) classes = [ "cms-placeholder-%s" % placeholder.pk, 'cms-placeholder', ] output = render_placeholder_toolbar(placeholder, context, 'test', 'en') for cls in classes: self.assertTrue(cls in output, '%r is not in %r' % (cls, output))
def test_render_placeholder_toolbar(self): placeholder = Placeholder() placeholder.slot = 'test' placeholder.pk = placeholder.id = 99 request = self.get_request(page=None) request.toolbar = CMSToolbar(request) content_renderer = self.get_content_renderer(request) context = SekizaiContext() context['request'] = request context['cms_content_renderer'] = content_renderer classes = [ "cms-placeholder-%s" % placeholder.pk, 'cms-placeholder', ] output = content_renderer.render_editable_placeholder(placeholder, context, 'en') for cls in classes: self.assertTrue(cls in output, '%r is not in %r' % (cls, output))
def test_render_placeholder_toolbar(self): placeholder = Placeholder() placeholder.slot = 'test' placeholder.pk = placeholder.id = 99 context = SekizaiContext() context['request'] = AttributeObject( REQUEST={'language': 'en'}, GET=[], session={}, path='/', user=self.test_user, current_page=None, method='GET', ) classes = [ "cms_placeholder-%s" % placeholder.pk, 'cms_placeholder', ] output = render_placeholder_toolbar(placeholder, context, 'test', 'en') for cls in classes: self.assertTrue(cls in output, '%r is not in %r' % (cls, output))
def convert(action = "dryrun"): # this dictionary store the information for the conversions execute=action models_dictionary = { "messages": {}, # a general set of messages for the user "modules": { "news_and_events.models": { # each module containing the models must be represented, like this "application": "News & Events", # this is the human-friendly name of the module "models": { # a dictionary with each model in that module "NewsArticle": { # the actual name of the class "fields": [ # a list of the fields we're working on { # a dictionary for each field "old_field": "content", "new_field": "body", "slot": "body", }, ], "model": "News articles", # the human-friendly name of the model "actions": {}, # an empty dictionary where we we store the results }, "Event": { # a second model in that module "fields": [ { "old_field": "content", "new_field": "body", "slot": "body", }, ], "model": "Events", "actions": {}, }, }, }, "vacancies_and_studentships.models": { # and a second module "application": "Vacancies & Studentships", "models": { "Vacancy": { "fields": [ { "old_field": "description", "new_field": "body", "slot": "body", }, ], "model": "Vacancies", "actions": {}, }, "Studentship": { "fields": [ { "old_field": "description", "new_field": "body", "slot": "body", }, ], "model": "Studentships", "actions": {}, }, }, }, "publications.models": { "application": "Publications", "models": { "Researcher": { "fields": [ { "old_field": "research_synopsis", "new_field": "synopsis", "slot": "body", }, { "old_field": "research_description", "new_field": "description", "slot": "body", }, ], "model": "Researcher", "actions": {}, }, }, }, }, } print "------executing --------" # loop over the modules for module, module_values in models_dictionary["modules"].items(): # loop over the models in the module for model, model_values in module_values["models"].items(): # mmodel is the human-readable name of the model, used for the report summary mmodel = models_dictionary["modules"][module]["models"][model]["model"] models_dictionary["messages"][mmodel]={} # import the model actual_model = getattr(__import__(module, globals(), locals(), module_values["models"], -1), model) # loop over the fields that need converting for field in model_values["fields"]: old_field = field["old_field"] new_field = field["new_field"] slot = field["slot"] # create a summary report for this field models_dictionary["messages"][mmodel][old_field]={} try: getattr(actual_model, new_field) except AttributeError: message = "field " + new_field + " is missing - check the model and try agin" models_dictionary["messages"][mmodel][old_field]["Error"]=message continue junk_content = [] # a record of those items with nothing but <br /> in them moved_items =[] # a record of the items we migrated to placeholders # loop over each item in the class for item in actual_model.objects.all(): old_field_content = getattr(item, old_field) # the old field we want to convert # now the serious business of converting the fields # if the item lacks a placeholder, create the placeholder and the reference to it if old_field_content and not getattr(item, new_field, None): # check to see if it's worth converting if len(old_field_content) > 10: # create the placeholder placeholder=Placeholder(slot=slot) if execute == "execute": placeholder.save() # refer to the placeholder from the item setattr(item, new_field, placeholder) if execute == "execute": add_plugin(placeholder, "SemanticTextPlugin", settings.CMS_LANGUAGES[0][0], body = old_field_content) # setattr(item, old_field, "") if execute == "execute": item.status = "Converted to placeholder" else: item.status = "Unconverted" else: # this item is so short it must be junk if execute == "execute": setattr(item, old_field, "") item.status = "Junk field - too short; was deleted instead of converted:" + old_field_content else: item.status = "Junk field - too short; will be deleted instead of converted:" + old_field_content # make a note that this was a junk item junk_content.append(item) # make a note that we moved this item moved_items.append(item) if execute == "execute": item.save() # information about junk content items if execute == "execute": message = " ".join((str(len(junk_content)), "junk items not converted items")) else: message = " ".join((str(len(junk_content)), "junk items found")) models_dictionary["messages"][mmodel][old_field]["Junk fields"]=message # information about items that have been/need to be converted if execute == "execute": message = str(len(moved_items)) + " items were converted to placeholder " + new_field else: message = str(len(moved_items)) + " items need to be converted to placeholder " + new_field models_dictionary["messages"][mmodel][old_field]["Conversions"]=message # list every item that was copied for the full report if execute == "execute": action = "Fields that were copied" else: action = "Fields to be copied" models_dictionary["modules"][module]["models"][model]["actions"][action]=moved_items report = { "action": execute, "task": "convert-placeholders", "converted": models_dictionary, "template": "housekeeping/convert_to_placeholders.html" } return report
def __init__(self, request): super(CMSToolbar, self).__init__() self.right_items = [] self.left_items = [] self.populated = False self.post_template_populated = False self.menus = {} self.request = request self.login_form = CMSToolbarLoginForm(request=request) self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get( 'cms_edit', False) self.edit_mode_url_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') self.edit_mode_url_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') self.build_mode = self.is_staff and self.request.session.get( 'cms_build', False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get( 'cms_edit', False) self.obj = None self.redirect_url = None if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language if self.is_staff: try: user_settings = UserSettings.objects.select_related( 'clipboard').get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() if (settings.USE_I18N and user_settings.language in dict( settings.LANGUAGES)) or (not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE): self.toolbar_language = user_settings.language else: user_settings.language = self.language user_settings.save() self.clipboard = user_settings.clipboard with force_language(self.language): try: decorator = resolve(self.request.path_info).func try: # If the original view is decorated we try to extract the real function # module instead of the decorator's one if decorator and getattr(decorator, 'func_closure', False): # python 2 self.app_name = decorator.func_closure[ 0].cell_contents.__module__ elif decorator and getattr(decorator, '__closure__', False): # python 3 self.app_name = decorator.__closure__[ 0].cell_contents.__module__ else: raise AttributeError() except (TypeError, AttributeError): # no decorator self.app_name = decorator.__module__ except Resolver404: self.app_name = "" toolbars = toolbar_pool.get_toolbars() parts = self.app_name.split('.') while parts: path = '.'.join(parts) if path in installed_apps(): self.app_name = path break parts.pop() self.toolbars = SortedDict() for key in toolbars: toolbar = toolbars[key](self.request, self, toolbars[key].check_current_app( key, self.app_name), self.app_name) self.toolbars[key] = toolbar
def __init__(self, request): super(CMSToolbar, self).__init__() self.right_items = [] self.left_items = [] self.populated = False self.post_template_populated = False self.menus = {} self.request = request self.login_form = CMSToolbarLoginForm(request=request) self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False) self.edit_mode_url_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') self.edit_mode_url_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') self.build_mode = self.is_staff and self.request.session.get('cms_build', False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False) self.obj = None self.redirect_url = None if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language if self.is_staff: try: user_settings = UserSettings.objects.select_related('clipboard').get(user=self.request.user) except UserSettings.DoesNotExist: user_settings = UserSettings(language=self.language, user=self.request.user) placeholder = Placeholder(slot="clipboard") placeholder.save() user_settings.clipboard = placeholder user_settings.save() if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or ( not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE): self.toolbar_language = user_settings.language else: user_settings.language = self.language user_settings.save() self.clipboard = user_settings.clipboard with force_language(self.language): try: decorator = resolve(self.request.path_info).func try: # If the original view is decorated we try to extract the real function # module instead of the decorator's one if decorator and getattr(decorator, 'func_closure', False): # python 2 self.app_name = decorator.func_closure[0].cell_contents.__module__ elif decorator and getattr(decorator, '__closure__', False): # python 3 self.app_name = decorator.__closure__[0].cell_contents.__module__ else: raise AttributeError() except (TypeError, AttributeError): # no decorator self.app_name = decorator.__module__ except Resolver404: self.app_name = "" toolbars = toolbar_pool.get_toolbars() parts = self.app_name.split('.') while parts: path = '.'.join(parts) if path in installed_apps(): self.app_name = path break parts.pop() self.toolbars = SortedDict() for key in toolbars: toolbar = toolbars[key](self.request, self, toolbars[key].check_current_app(key, self.app_name), self.app_name) self.toolbars[key] = toolbar
def convert(request, slug = "dryrun"): # this dictionary store the information for the conversions execute=slug models_dictionary = { "messages": {}, # a general set of messages for the user "modules": { "news_and_events.models": { # each module containing the models must be represented, like this "application": "News & Events", # this is the human-friendly name of the module "models": { # a dictionary with each model in that module "NewsArticle": { # the actual name of the class "fields": [ # a list of the fields we're working on { # a dictionary for each field "old_field": "content", "new_field": "body", "slot": "body", }, ], "model": "News articles", # the human-friendly name of the model "actions": {}, # an empty dictionary where we we store the results }, "Event": { # a second model in that module "fields": [ { "old_field": "content", "new_field": "body", "slot": "body", }, ], "model": "Events", "actions": {}, }, }, }, "vacancies_and_studentships.models": { # and a second module "application": "Vacancies & Studentships", "models": { "Vacancy": { "fields": [ { "old_field": "description", "new_field": "body", "slot": "body", }, ], "model": "Vacancies", "actions": {}, }, "Studentship": { "fields": [ { "old_field": "description", "new_field": "body", "slot": "body", }, ], "model": "Studentships", "actions": {}, }, }, }, "publications.models": { "application": "Publications", "models": { "Researcher": { "fields": [ { "old_field": "research_synopsis", "new_field": "synopsis_of_research", "slot": "body", }, { "old_field": "research_description", "new_field": "description_of_research", "slot": "body", }, ], "model": "Researcher", "actions": {}, }, }, }, }, } # loop over the modules for module, module_values in models_dictionary["modules"].items(): # loop over the models in the module for model, model_values in module_values["models"].items(): # mmodel is the human-readable name of the model, used for the report summary mmodel = models_dictionary["modules"][module]["models"][model]["model"] models_dictionary["messages"][mmodel]={} # import the model actual_model = getattr(__import__(module, globals(), locals(), module_values["models"], -1), model) # loop over the fields that need converting for field in model_values["fields"]: print field old_field = field["old_field"] new_field = field["new_field"] slot = field["slot"] # create a summary report for this field models_dictionary["messages"][mmodel][old_field]={} try: getattr(actual_model, new_field) except AttributeError: message = "field " + new_field + " is missing - check the model and try agin" models_dictionary["messages"][mmodel][old_field]["Error"]=message continue junk_content = [] # a record of those items with nothing but <br /> in them moved_items =[] # a record of the items we migrated to placeholders # loop over each item in the class for item in actual_model.objects.all(): old_field_content = getattr(item, old_field) # the old field we want to convert # first get rid of junk content (change "<br />" to "") if old_field_content == "<br />": old_field_content = "" setattr(item, old_field, "") # item.content = "" if execute == "convert": item.save() # now the serious business of converting the fields # if the item lacks a placeholder, create the placeholder and the reference to it if old_field_content and not getattr(item, new_field, None): # check to see if it's worth converting if len(old_field_content) > 60: # create the placeholder placeholder=Placeholder(slot=slot) if execute == "convert": placeholder.save() # refer to the placeholder from the item setattr(item, new_field, placeholder) # I copied this from one of the test files plugin_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=1, language=settings.LANGUAGES[0][0]) # we assume the original field was in the first language plugin_base.insert_at(None, position='last-child', commit=False) # create a text plugin plugin = Text(body='') plugin_base.set_base_attr(plugin) plugin.body = getattr(item, old_field) if execute == "convert": plugin.save() # set the old field to "" setattr(item, old_field, "") if execute == "convert": item.save() item.status = "Converted to placeholder" else: item.status = "Unconverted" else: print "too short", old_field_content # this item is so short it must be junk if execute == "convert": setattr(item, old_field, "") item.status = "Junk field - too short; was deleted instead of converted:" + old_field_content item.save() else: item.status = "Junk field - too short; will be deleted instead of converted:" + old_field_content # make a note that this was a junk item junk_content.append(item) # make a note that we moved this item moved_items.append(item) # information about junk content items if execute == "convert": message = " ".join((str(len(junk_content)), "junk items not converted items")) else: message = " ".join((str(len(junk_content)), "junk items found")) models_dictionary["messages"][mmodel][old_field]["Junk fields"]=message # information about items that have been/need to be converted if execute == "convert": message = str(len(moved_items)) + " items were converted to placeholder " + new_field else: message = str(len(moved_items)) + " items need to be converted to placeholder " + new_field models_dictionary["messages"][mmodel][old_field]["Conversions"]=message # list every item that was copied for the full report if execute == "convert": action = "Fields that were copied" else: action = "Fields to be copied" models_dictionary["modules"][module]["models"][model]["actions"][action]=moved_items return shortcuts.render_to_response( "housekeeping/convert_to_placeholders.html", { "execute": execute, "converted": models_dictionary, }, RequestContext(request), )