def test_get_page_by_untyped_arg_dict_fail_nodebug_no_email(self): with SettingsOverride(SEND_BROKEN_LINK_EMAILS=False, DEBUG=False, MANAGERS=[("Jenkins", "*****@*****.**")]): request = self.get_request('/') page = _get_page_by_untyped_arg({'pk': 1003}, request, 1) self.assertEqual(page, None) self.assertEqual(len(mail.outbox), 0)
def get_page_tags_from_request(request, page_lookup, lang, site, title=False): """ Get the list of tags attached to a Page or a Title from a request from usual `page_lookup` parameters. :param request: request object :param page_lookup: a valid page_lookup argument :param lang: a language code :param site: a site id :param title: a boolean to extract the Page (if False) or Title instance :return: list of tags :type: List """ from cms.templatetags.cms_tags import _get_page_by_untyped_arg from cms.utils import get_language_from_request, get_cms_setting, get_site_id from django.core.cache import cache site_id = get_site_id(site) if lang is None: lang = get_language_from_request(request) cache_key = get_cache_key(request, page_lookup, lang, site, title) tags_list = cache.get(cache_key) if not tags_list: page = _get_page_by_untyped_arg(page_lookup, request, site_id) if page: if title: tags_list = get_title_tags(page, lang) else: tags_list = get_page_tags(page) cache.set(cache_key, tags_list, timeout=get_cms_setting('CACHE_DURATIONS')['content']) if not tags_list: tags_list = () return tags_list
def test_get_page_by_pk_arg_edit_mode(self): control = self._getfirst() request = self.get_request('/') request.GET = {"edit": ''} user = User(username="******", password="******", is_superuser=True, is_staff=True, is_active=True) user.save() request.current_page = control request.user = user page = _get_page_by_untyped_arg(control.pk, request, 1) self.assertEqual(page, control.publisher_draft)
def _show_placeholder_attr_for_page( context, placeholder_name, plugin_class_name, plugin_attr, page_lookup, lang=None, site=None, cache_result=True): validate_placeholder_name(placeholder_name) request = context.get('request', False) site_id = get_site_id(site) if not request: return {'content': ''} if lang is None: lang = get_language_from_request(request) if cache_result: base_key = _get_cache_key( '_show_placeholder_for_page', page_lookup, lang, site_id) cache_key = _clean_key( '%s_placeholder:%s' % ( base_key, placeholder_name )) + plugin_class_name + '.' + plugin_attr cached_value = cache.get(cache_key) if isinstance(cached_value, dict): # new style _restore_sekizai(context, cached_value['sekizai']) return {'content': mark_safe(cached_value['content'])} elif isinstance(cached_value, string_types): # old style return {'content': mark_safe(cached_value)} page = _get_page_by_untyped_arg(page_lookup, request, site_id) if not page: return {'content': ''} watcher = Watcher(context) placeholder = _get_placeholder(page, page, context, placeholder_name) content = get_placholder_attr( placeholder, placeholder_name, plugin_class_name, plugin_attr) changes = watcher.get_changes() if cache_result: cache.set( cache_key, { 'content': content, 'sekizai': changes }, get_cms_setting('CACHE_DURATIONS')['content']) if content: return {'content': mark_safe(content)} return {'content': ''}
def test_get_page_by_pk_arg_edit_mode(self): control = self._getfirst() request = self.get_request('/') request.GET = {"edit": ''} user = self._create_user("admin", True, True) request.current_page = control request.user = user middleware = ToolbarMiddleware() middleware.process_request(request) page = _get_page_by_untyped_arg(control.pk, request, 1) self.assertEqual(page, control.publisher_draft)
def _show_content_for_page(context, placeholder_name, page_lookup, lang=None, site=None, cache_result=True, content_max_length=None): """ Shows the content of a page as content of placeholder with name 'content' and given lookup arguments in the given language. This is useful if you want to have some more or less static content that is shared among many pages, such as a footer. See _get_page_by_untyped_arg() for detailed information on the allowed types and their interpretation for the page_lookup argument. """ validate_placeholder_name(placeholder_name) request = context.get('request', False) site_id = get_site_id(site) if not request: return {'content': ''} if lang is None: lang = get_language_from_request(request) if cache_result: base_key = _get_cache_key('_show_content_for_page', page_lookup, lang, site_id) cache_key = _clean_key('%s_placeholder:%s' % (base_key, placeholder_name)) cached_value = cache.get(cache_key) if isinstance(cached_value, dict): # new style _restore_sekizai(context, cached_value['sekizai']) return {'content': mark_safe(cached_value['content'])} elif isinstance(cached_value, basestring): # old style return {'content': mark_safe(cached_value)} page = _get_page_by_untyped_arg(page_lookup, request, site_id) if not page: return {'content': ''} try: placeholder = page.placeholders.get(slot=placeholder_name) except PlaceholderModel.DoesNotExist: if settings.DEBUG: raise return {'content': ''} watcher = Watcher(context) content = render_placeholder(placeholder, context, placeholder_name) if content_max_length: content = remove_tags(content)[:content_max_length] changes = watcher.get_changes() if cache_result: cache.set(cache_key, {'content': content, 'sekizai': changes}, get_cms_setting('CACHE_DURATIONS')['content']) if content: return {'content': mark_safe(content)} return {'content': ''}
def get_cache_key(request, page, lang, site_id, title): """ Create the cache key for the current page and tag type """ from cms.models import Page from cms.templatetags.cms_tags import _get_page_by_untyped_arg, _get_cache_key if not isinstance(page, Page): page = _get_page_by_untyped_arg(page, request, site_id) if not site_id: site_id = page.site_id if not title: return _get_cache_key('page_tags', page, '', site_id) + '_type:tags_list' else: return _get_cache_key('title_tags', page, lang, site_id) + '_type:tags_list'
def render_tag(self, context, page, site_id): request = context.get('request') if not site_id: site_id = get_current_site(request).pk if not page: page = request.current_page else: page = _get_page_by_untyped_arg(page, request, site_id) content = [] if not page: return '' try: if page.pagesitemapproperties.noindex: content.append('noindex') if page.pagesitemapproperties.noarchive: content.append('noarchive') if page.pagesitemapproperties.robots_extra: content.append(page.pagesitemapproperties.robots_extra) return '<meta name="robots" content="%s">' % ','.join(content) except ObjectDoesNotExist: return ''
def get_nodes(self, request): nodes = [] menu_id = 1000 page = _get_page_by_untyped_arg('project-landing', request, settings.SITE_ID) nodes.append(NavigationNode( 'Projects Overview', page.get_absolute_url(), page.id )) for project in Project.objects.filter(topic__isnull=True): # the menu tree consists of NavigationNode instances # Each NavigationNode takes a label as its first argument, a URL as # its second argument and a (for this tree) unique id as its third # argument. node = NavigationNode( project.title, project.get_absolute_url(), menu_id ) nodes.append(node) menu_id += 1 for topic in Topic.objects.all(): node = NavigationNode( topic.title, '', menu_id ) nodes.append(node) menu_id += 1 for project in topic.project_set.all(): node = NavigationNode( project.title, project.get_absolute_url(), menu_id ) nodes.append(node) menu_id += 1 return nodes
def test_get_page_by_untyped_arg_dict(self): second = self._getsecond() request = self.get_request('/') page = _get_page_by_untyped_arg({'pk': second.pk}, request, 1) self.assertEqual(page, second)
def test_get_page_by_untyped_arg_reverse_id(self): second = self._getsecond() request = self.get_request('/') page = _get_page_by_untyped_arg("myreverseid", request, 1) self.assertEqual(page, second)
def test_get_page_by_untyped_arg_page(self): control = self._getfirst() request = self.get_request('/') page = _get_page_by_untyped_arg(control, request, 1) self.assertEqual(page, control)
def test_get_page_by_untyped_arg_none(self): control = self._getfirst() request = self.get_request('/') request.current_page = control page = _get_page_by_untyped_arg(None, request, 1) self.assertEqual(page, control)
def details(request, slug): """ The main view of the Django-CMS! Takes a request and a slug, renders the page. """ # get the right model context = RequestContext(request) subdomain=request.META['HTTP_HOST'] if subdomain[:4]=='www.': subdomain=subdomain[4:] if (subdomain[-6:]=='com.ua' and subdomain.count('.')>=3) or (subdomain[-6:]!='com.ua' and subdomain.count('.')>=2): subdomain=subdomain[:subdomain.find('.')] else: subdomain='' main_domain=request.META['HTTP_HOST'] if subdomain!='': main_domain=main_domain[len(subdomain)+1:] if subdomain and subdomain!='etalon' and not subdomain.endswith('dev'): try: obl=Site.objects.get_current().obl.get(subdomain=subdomain) except: return HttpResponseRedirect('http://'+main_domain+request.get_full_path()) else: if request.location and request.location.custom_region: try: obl=Site.objects.get_current().obl.get(slug=request.location.custom_region.slug) return HttpResponseRedirect('http://'+request.location.custom_region.subdomain+'.'+main_domain+request.get_full_path()) except: pass # import logging # logging.info('dm='+request.META['HTTP_HOST']) # logging.info('sbd='+subdomain) # logging.info('mdm='+main_domain) # logging.info('loc='+location(request)['loc']) # # Get a Page model object from the request page = get_page_from_request(request, use_path=slug) if not page: return _handle_no_page(request, slug) current_language = get_language_from_request(request) # Check that the current page is available in the desired (current) language available_languages = [] page_languages = page.get_languages() user_languages = get_public_languages() if hasattr(request, 'user') and request.user.is_staff: user_languages = get_language_list() for frontend_lang in user_languages: if frontend_lang in page_languages: available_languages.append(frontend_lang) attrs = '' if 'edit' in request.GET: attrs = '?edit=1' elif 'preview' in request.GET: attrs = '?preview=1' if 'draft' in request.GET: attrs += '&draft=1' # Check that the language is in FRONTEND_LANGUAGES: if not current_language in user_languages: #are we on root? if not slug: #redirect to supported language languages = [] for language in available_languages: languages.append((language, language)) if languages: with SettingsOverride(LANGUAGES=languages, LANGUAGE_CODE=languages[0][0]): #get supported language new_language = get_language_from_request(request) if new_language in get_public_languages(): with force_language(new_language): pages_root = reverse('pages-root') return HttpResponseRedirect(pages_root + attrs) else: _handle_no_page(request, slug) else: return _handle_no_page(request, slug) if current_language not in available_languages: # If we didn't find the required page in the requested (current) # language, let's try to find a fallback found = False for alt_lang in get_fallback_languages(current_language): if alt_lang in available_languages: if get_redirect_on_fallback(current_language): with force_language(alt_lang): path = page.get_absolute_url(language=alt_lang, fallback=True) # In the case where the page is not available in the # preferred language, *redirect* to the fallback page. This # is a design decision (instead of rendering in place)). return HttpResponseRedirect(path + attrs) else: found = True if not found: # There is a page object we can't find a proper language to render it _handle_no_page(request, slug) if apphook_pool.get_apphooks(): # There are apphooks in the pool. Let's see if there is one for the # current page # since we always have a page at this point, applications_page_check is # pointless # page = applications_page_check(request, page, slug) # Check for apphooks! This time for real! try: app_urls = page.get_application_urls(current_language, False) except Title.DoesNotExist: app_urls = [] if app_urls: app = apphook_pool.get_apphook(app_urls) pattern_list = [] for urlpatterns in get_app_urls(app.urls): pattern_list += urlpatterns urlpatterns = patterns('', *pattern_list) try: context.current_app = page.reverse_id if page.reverse_id else app.app_name view, args, kwargs = resolve('/', tuple(urlpatterns)) return view(request, *args, **kwargs) except Resolver404: pass # Check if the page has a redirect url defined for this language. redirect_url = page.get_redirect(language=current_language) if redirect_url: if redirect_url.startswith('reverse_id:'): slug=cms_tags._get_page_by_untyped_arg(redirect_url.split(':')[1], request, Site.objects.get_current().id).get_absolute_url() return HttpResponsePermanentRedirect(slug) else: if (is_language_prefix_patterns_used() and redirect_url[0] == "/" and not redirect_url.startswith('/%s/' % current_language)): # add language prefix to url redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/")) # prevent redirect to self own_urls = [ 'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path), '/%s' % request.path, request.path, ] if redirect_url not in own_urls: return HttpResponsePermanentRedirect(redirect_url + attrs) # permission checks if page.login_required and not request.user.is_authenticated(): path = urlquote(request.get_full_path()) tup = settings.LOGIN_URL, "next", path return HttpResponseRedirect('%s?%s=%s' % tup) template_name = get_template_from_request(request, page, no_current_page=True) # fill the context context['lang'] = current_language context['current_page'] = page context['has_change_permissions'] = page.has_change_permission(request) context['has_view_permissions'] = page.has_view_permission(request) if not context['has_view_permissions']: return _handle_no_page(request, slug) return render_to_response(template_name, context_instance=context)
def _show_content_for_page(context, placeholder_name, page_lookup, lang=None, site=None, cache_result=True, content_max_length=None): """ Shows the content of a page as content of placeholder with name 'content' and given lookup arguments in the given language. This is useful if you want to have some more or less static content that is shared among many pages, such as a footer. See _get_page_by_untyped_arg() for detailed information on the allowed types and their interpretation for the page_lookup argument. """ validate_placeholder_name(placeholder_name) request = context.get('request', False) site_id = get_site_id(site) if not request: return {'content': ''} if lang is None: lang = get_language_from_request(request) if cache_result: base_key = _get_cache_key('_show_content_for_page', page_lookup, lang, site_id) cache_key = _clean_key('%s_placeholder:%s' % (base_key, placeholder_name)) cached_value = cache.get(cache_key) if isinstance(cached_value, dict): # new style _restore_sekizai(context, cached_value['sekizai']) return {'content': mark_safe(cached_value['content'])} elif isinstance(cached_value, basestring): # old style return {'content': mark_safe(cached_value)} page = _get_page_by_untyped_arg(page_lookup, request, site_id) if not page: return {'content': ''} try: placeholder = page.placeholders.get(slot=placeholder_name) except PlaceholderModel.DoesNotExist: if settings.DEBUG: raise return {'content': ''} watcher = Watcher(context) content = render_placeholder(placeholder, context, placeholder_name) if content_max_length: content = remove_tags(content)[:content_max_length] changes = watcher.get_changes() if cache_result: cache.set(cache_key, { 'content': content, 'sekizai': changes }, get_cms_setting('CACHE_DURATIONS')['content']) if content: return {'content': mark_safe(content)} return {'content': ''}
def test_get_page_by_untyped_arg_dict_fail_nodebug(self): with SettingsOverride(DEBUG=False, MANAGERS=[("Jenkins", "*****@*****.**")]): request = self.get_request("/") page = _get_page_by_untyped_arg({"pk": 3}, request, 1) self.assertEqual(page, None) self.assertEqual(len(mail.outbox), 1)