def test_duplicate_slug(self):
        from wagtail.wagtailcore.models import Site
        # Create a test Site with a root page
        root = models.TestRootPage(title='title', depth=1, path='0001', slug_en='slug_en', slug_de='slug_de')
        root.save()

        site = Site(root_page=root)
        site.save()

        # Add children to the root
        child = root.add_child(
            instance=models.TestSlugPage1(title='child1', slug_de='child', slug_en='child-en', depth=2, path='00010001')
        )

        child2 = root.add_child(
            instance=models.TestSlugPage2(title='child2', slug_de='child-2', slug_en='child2-en', depth=2,
                                          path='00010002')
        )

        # Clean should work fine as the two slugs are different
        child2.clean()

        # Make the slug equal to test if the duplicate is detected
        child2.slug_de = 'child'

        self.assertRaises(ValidationError, child2.clean)
Ejemplo n.º 2
0
    def test_oops_there_is_more_than_one(self):
        Site.objects.create(hostname="example.com", is_default_site=True, root_page=Page.objects.get(pk=2))

        site = Site(hostname="test.com", is_default_site=True, root_page=Page.objects.get(pk=2))
        with self.assertRaises(Site.MultipleObjectsReturned):
            # If there already are multiple default sites, you're in trouble
            site.clean_fields()
Ejemplo n.º 3
0
    def test_duplicate_slug(self):
        from wagtail.wagtailcore.models import Site
        # Create a test Site with a root page
        root = models.TestRootPage(title='title', depth=1, path='0001', slug_en='slug_en', slug_de='slug_de')
        root.save()

        site = Site(root_page=root)
        site.save()

        # Add children to the root
        child = root.add_child(
            instance=models.TestSlugPage1(title='child1', slug_de='child', slug_en='child-en', depth=2, path='00010001')
        )

        child2 = root.add_child(
            instance=models.TestSlugPage2(title='child2', slug_de='child-2', slug_en='child2-en', depth=2,
                                          path='00010002')
        )

        # Clean should work fine as the two slugs are different
        child2.clean()

        # Make the slug equal to test if the duplicate is detected
        child2.slug_de = 'child'

        self.assertRaises(ValidationError, child2.clean)
Ejemplo n.º 4
0
    def test_set_url_path(self):
        from wagtail.wagtailcore.models import Site
        # Create a test Site with a root page
        root = models.TestRootPage(title='url paths', depth=1, path='0006', slug='url-path-slug')
        root.save()

        site = Site(root_page=root)
        site.save()

        # Add children to the root
        child = root.add_child(
            instance=models.TestSlugPage1(title='child', slug='child', depth=2, path='00060001')
        )
        child.save()

        # Add grandchildren to the root
        grandchild = child.add_child(
            instance=models.TestSlugPage1(title='grandchild', slug='grandchild', depth=2, path='000600010001')
        )
        grandchild.save()

        self.assertEqual(child.url_path_de, '/child/')
        self.assertEqual(child.url_path_en, '/child/')
        self.assertEqual(grandchild.url_path_de, '/child/grandchild/')
        self.assertEqual(grandchild.url_path_en, '/child/grandchild/')

        grandchild.slug_de = 'grandchild1'
        grandchild.save()

        self.assertEqual(grandchild.url_path_de, '/child/grandchild1/')
        self.assertEqual(grandchild.url_path_en, '/child/grandchild1/')

        grandchild.slug_en = 'grandchild1_en'
        grandchild.save()

        self.assertEqual(grandchild.url_path_de, '/child/grandchild1/')
        self.assertEqual(grandchild.url_path_en, '/child/grandchild1_en/')

        # Children url paths should update when parent changes
        child.slug_en = 'child_en'
        child.save()

        self.assertEqual(child.url_path_de, '/child/')
        self.assertEqual(child.url_path_en, '/child_en/')

        # We should retrieve grandchild with the below command:
        # grandchild_new = models.TestSlugPage1.objects.get(id=grandchild.id)
        # but it's exhibiting strange behaviour during tests. See:
        # https://github.com/infoportugal/wagtail-modeltranslation/issues/103#issuecomment-352006610
        grandchild_new = models.TestSlugPage1._default_manager.raw("""
            SELECT page_ptr_id, url_path_en, url_path_de FROM {}
            WHERE page_ptr_id=%s LIMIT 1
        """.format(models.TestSlugPage1._meta.db_table), [grandchild.page_ptr_id])[0]
        self.assertEqual(grandchild_new.url_path_en, '/child_en/grandchild1_en/')
        self.assertEqual(grandchild_new.url_path_de, '/child/grandchild1/')
Ejemplo n.º 5
0
    def test_relative_url(self):
        from wagtail.wagtailcore.models import Site
        # Create a test Site with a root page
        root = models.TestRootPage(title='title slugurl',
                                   depth=1,
                                   path='0004',
                                   slug_en='title_slugurl_en',
                                   slug_de='title_slugurl_de')
        root.save()
        site = Site(root_page=root)
        site.save()

        # Add children to the root
        child = root.add_child(
            instance=models.TestSlugPage1(title='child1 slugurl',
                                          slug_en='child-slugurl-en',
                                          slug_de='child-slugurl-de',
                                          depth=2,
                                          path='00040001'))
        child.save_revision().publish()

        url_1_de = child.relative_url(site)
        self.assertEqual(
            url_1_de, '/de/child-slugurl-de/',
            'When using the default language, slugurl produces the wrong url.')

        trans_real.activate('en')

        url_1_en = child.relative_url(site)
        self.assertEqual(
            url_1_en, '/en/child-slugurl-en/',
            'When using non-default language, slugurl produces the wrong url.')

        # Add children using non-default language
        child2 = root.add_child(
            instance=models.TestSlugPage2(title='child2 slugurl',
                                          title_de='child2 slugurl DE',
                                          slug_de='child2-slugurl-de',
                                          slug_en='child2-slugurl-en',
                                          depth=2,
                                          path='00040002'))
        child2.save_revision().publish()

        url_2_en = child2.relative_url(site)
        self.assertEqual(
            url_2_en, '/en/child2-slugurl-en/',
            'When using non-default language, slugurl produces the wrong url.')

        trans_real.activate('de')

        url_2_de = child2.relative_url(site)
        self.assertEqual(
            url_2_de, '/de/child2-slugurl-de/',
            'When using non-default language, slugurl produces the wrong url.')
Ejemplo n.º 6
0
    def test_oops_there_is_more_than_one(self):
        Site.objects.create(hostname='example.com',
                            is_default_site=True,
                            root_page=Page.objects.get(pk=2))

        site = Site(hostname='test.com',
                    is_default_site=True,
                    root_page=Page.objects.get(pk=2))
        with self.assertRaises(Site.MultipleObjectsReturned):
            # If there already are multiple default sites, you're in trouble
            site.clean_fields()
Ejemplo n.º 7
0
def home_page():
    rp = root_page()
    rp.get_children().delete()
    hp = root_page().add_child(
        instance=FrontPage(title='Test Home', live=True))
    site = Site(hostname='localhost',
                is_default_site=True,
                port=80,
                site_name='Test site',
                root_page=hp)
    site.save()
    return hp
Ejemplo n.º 8
0
    def test_get_unit_chat_link(self):
        """
        Test that pages in the site get the correct ask a librarian 
        link to their corresoinding AskPage and chat widget. Eckhart 
        and SCRC are treated differently since they're circumstances
        are slightly different.
        """
        ask_widgets = set(['law', 'crerar', 'ssa', 'uofc-ask', 'dissertation-office'])

        # Dictionary of tuples where the keys map to the ask_widget_name field  
        # of AskPages. The firs item of the tuple is a mixed dictionary of 
        # location/hours/unit information and the second item of the tuple is 
        # a random url belonging to a page of a given section of the site.
        data = {
            'law': (get_hours_and_location(StandardPage.objects.get(id=DANGELO_HOMEPAGE)), '/law/services/carrelslockers/'),
            'crerar': (get_hours_and_location(StandardPage.objects.get(id=CRERAR_HOMEPAGE)), '/crerar/science-research-services/data-support-services/'),
            'ssa': (get_hours_and_location(StandardPage.objects.get(id=SSA_HOMEPAGE)), '/ssa/about/'),
            'uofc-ask': (get_hours_and_location(StandardPage.objects.get(id=PUBLIC_HOMEPAGE)), '/research/help/offcampus/'),
            'dissertation-office': (get_hours_and_location(StandardPage.objects.get(id=DISSERTATION_HOMEPAGE)), '/research/scholar/phd/students/'),
            'eck': (get_hours_and_location(StandardPage.objects.get(id=ECKHART_HOMEPAGE)), '/eck/mathematics-research-services/'),
            'scrc': (get_hours_and_location(StandardPage.objects.get(id=SCRC_HOMEPAGE)), '/scrc/visiting/'),
        }

        # Normal chat links to regular AskPages
        for item in ask_widgets:
            request = HttpRequest()
            request.path = data[item][1]
            current_site = Site.find_for_request(request)

            a = get_unit_chat_link(data[item][0]['page_unit'], request)
            b = AskPage.objects.filter(ask_widget_name=item).first().relative_url(current_site)

            self.assertEqual(a, b)

        # Eckhart
        request_eck = HttpRequest()
        request_eck.path = data['eck'][1]
        current_site = Site.find_for_request(request_eck)
        eckurl = get_unit_chat_link(data['eck'][0]['page_unit'], request_eck)
        eckask = AskPage.objects.get(id=4646).relative_url(current_site)
        self.assertEqual(eckurl, eckask)


        # SCRC
        request_scrc = HttpRequest()
        request_scrc.path = data['scrc'][1]
        current_site = Site.find_for_request(request_scrc)
        scrcurl = get_unit_chat_link(data['scrc'][0]['page_unit'], request_scrc)
        scrcask = PublicRawHTMLPage.objects.get(id=4127).relative_url(current_site)
        self.assertEqual(scrcurl, scrcask)
Ejemplo n.º 9
0
 def get_context(self, request):
     context = super(ConferenceSubPage, self).get_context(request)
     current_site = Site.find_for_request(request)
     context['banner_image'] = self.get_parent().conferencepage.banner_image
     context['branding_color'] = self.get_parent().conferencepage.branding_color
     context['conference_logo'] = self.get_parent().conferencepage.conference_logo 
     context['conference_title'] = self.get_parent().title
     context['conference_subtitle'] = self.get_parent().conferencepage.subtitle
     context['conference_tagline'] = self.get_parent().conferencepage.tagline
     context['has_social_media'] = self.get_parent().conferencepage.has_social_media
     context['main_registration'] = self.get_parent().conferencepage.main_registration.all()
     context['sponsors'] = self.get_parent().conferencepage.sponsors.all()
     context['organizers'] = self.get_parent().conferencepage.organizers.all()
     context['twitter_page'] = self.get_parent().conferencepage.twitter_page 
     context['facebook_page'] = self.get_parent().conferencepage.facebook_page
     context['hashtag_page'] = self.get_parent().conferencepage.hashtag_page
     context['hashtag'] = self.get_parent().conferencepage.hashtag
     context['instagram_page'] = self.get_parent().conferencepage.instagram_page
     context['youtube_page'] = self.get_parent().conferencepage.youtube_page
     context['blog_page'] = self.get_parent().conferencepage.blog_page
     context['tumblr_page'] = self.get_parent().conferencepage.tumblr_page
     context['snapchat_page'] = self.get_parent().conferencepage.snapchat_page
     context['secondary_registration'] = self.get_parent().conferencepage.sub_registration.all()
     context['secondary_registration_heading'] = self.get_parent().conferencepage.secondary_registration_heading
     context['secondary_registration_description'] = self.get_parent().conferencepage.secondary_registration_description
     context['home'] = self.get_parent().conferencepage.relative_url(current_site)
     return context
Ejemplo n.º 10
0
    def get_context(self, request):
        this_site = Site.find_for_request(request)
        context = super(ArticlesIndexPage, self).get_context(request)

        all_articles = ArticlePage.objects.live().order_by(
            '-first_published_at')

        site_articles = [
            article for article in all_articles
            if article.get_site() == this_site
        ]

        paginator = Paginator(site_articles, 20)

        page = request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            articles = paginator.page(paginator.num_pages)

        context['articles'] = articles

        return context
Ejemplo n.º 11
0
def test_test(rf, site):
    request = HttpRequest()
    request.path = '/'
    request.META['HTTP_HOST'] = 'localhost'
    request.META['SERVER_PORT'] = 8000

    assert Site.find_for_request(request) == site
Ejemplo n.º 12
0
def scan(request):
    site = Site.find_for_request(request)
    broken_links = broken_link_scan(site)

    return render(request, 'wagtaillinkchecker/results.html', {
        'broken_links': broken_links,
    })
Ejemplo n.º 13
0
    def get_context(self, request):
        context = super(HomePage, self).get_context(request)

        this_site = Site.find_for_request(request)

        all_articles = ArticlePage.objects.live().order_by('-datum')

        site_articles = [
            article for article in all_articles
            if article.get_site() == this_site
        ]

        paginator = Paginator(site_articles, 5)

        page = request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            articles = paginator.page(paginator.num_pages)

        context['articles'] = articles
        context['naechster_termin'] = Termin.get_next(request)
        context['sites'] = Site.objects.order_by('site_name').all()

        return context
Ejemplo n.º 14
0
    def get_context(self, request):
        context = super(ConferenceSubPage, self).get_context(request)
        current_site = Site.find_for_request(request)
        parent = self.get_parent_of_type('conference page')
        main_reg = parent.main_registration.all()
        has_sidebar = parent.has_left_sidebar(context) or bool(main_reg)

        # Set social media fields dynamically and
        # get all the values from the parent page.
        # This doesn't seem like a good practice
        # How else can this be done?
        social_media_fields = [
            f.name for f in SocialMediaFields._meta.get_fields()
        ]
        for field in social_media_fields:
            exec('self.' + field + ' = ' + 'parent.' + field)

        context['primary_branding_color'] = parent.primary_branding_color
        context['secondary_branding_color'] = parent.secondary_branding_color
        context['conference_logo'] = parent.conference_logo
        context['conference_title'] = parent.title
        context['has_social_media'] = parent.has_social_media
        context['main_registration'] = parent.main_registration.all()
        context['sponsors'] = parent.sponsors.all()
        context['organizers'] = parent.organizers.all()
        context['secondary_registration'] = parent.sub_registration.all()
        context[
            'secondary_registration_heading'] = parent.secondary_registration_heading
        context[
            'secondary_registration_description'] = parent.secondary_registration_description
        context['home'] = parent.relative_url(current_site)
        return context
Ejemplo n.º 15
0
 def test_valid_headers_route_to_specific_site(self):
     # requests with a known Host: header should be directed to the specific site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.events_site.hostname
     request.META['SERVER_PORT'] = self.events_site.port
     self.assertEqual(Site.find_for_request(request), self.events_site)
Ejemplo n.º 16
0
 def test_port_in_http_host_header_is_ignored(self):
     # port in the HTTP_HOST header is ignored
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = "%s:%s" % (self.events_site.hostname, self.events_site.port)
     request.META['SERVER_PORT'] = self.alternate_port_events_site.port
     self.assertEqual(Site.find_for_request(request), self.alternate_port_events_site)
Ejemplo n.º 17
0
 def _import_pages (self, exported_page_data):
     # Delete any existing pages.
     for page in Page.objects.all():
         page.delete()
     with open(exported_page_data, 'r') as fh:
         page_data = cPickle.load(fh)
     for page_name, info in page_data.items():
         self.logger.debug('Creating page {}'.format(page_name))
         page = info['class'](**info['kwargs'])
         page.save()
         self._pages[page_name] = page
     # Add a Wagtail Site, or nothing will appear anywhere.
     home_page = HomePage.objects.all()[0]
     site = Site(hostname='localhost', root_page=home_page,
                 is_default_site=True)
     site.save()
def get_base_url():
    try:
        _id, root_path, root_url = Site.get_site_root_paths()[0]
        return root_url
    except IndexError:
        pass
    return None
Ejemplo n.º 19
0
def settings(request):
    site = Site.find_for_request(request)
    instance = SitePreferences.objects.filter(site=site).first()
    form = SitePreferencesForm(instance=instance)
    form.instance.site = site
    EditHandler = get_edit_handler(SitePreferences)

    if request.method == "POST":
        instance = SitePreferences.objects.filter(site=site).first()
        form = SitePreferencesForm(request.POST, instance=instance)
        if form.is_valid():
            edit_handler = EditHandler(instance=SitePreferences, form=form)
            form.save()
            messages.success(request, _('Link checker settings have been updated.'))
            return redirect('wagtaillinkchecker_settings')
        else:
            messages.error(request, _('The form could not be saved due to validation errors'))
    else:
        form = SitePreferencesForm(instance=instance)
        edit_handler = EditHandler(instance=SitePreferences, form=form)

    return render(request, 'wagtaillinkchecker/settings.html', {
        'form': form,
        'edit_handler': edit_handler,
    })
Ejemplo n.º 20
0
 def test_with_server_name(self):
     request = HttpRequest()
     request.META = {
         'SERVER_NAME': 'example.com',
         'SERVER_PORT': 80
     }
     self.assertEqual(Site.find_for_request(request), self.site)
Ejemplo n.º 21
0
def live_preview(request):

    try:
        if u'/' == request.path:
            page = Site.find_for_request(request).root_page.specific
        else:
            logger.info("path: %s", '//'+request.path)
            page = Page.objects.get(url_path='//'+request.path).specific
    except Page.DoesNotExist:
        return {}

    content_file = os.path.join(settings.BOOTSTRAP_CONTENT_DIR, 'pages', request.path.strip('/') + '.yml')
    if not os.path.isfile(content_file):
        return {}

    content_attributes = load_attributes_from_file(content_file)

    try:
        del content_attributes['type']
    except KeyError:
        pass

    SiteNode.set_page_attributes(page, content_attributes, get_relation_mappings())

    return {'self': page}
Ejemplo n.º 22
0
 def get_context(self, request):
     context = super(ConferencePage, self).get_context(request)
     current_site = Site.find_for_request(request)
     main_reg = self.main_registration.all()
     has_sidebar = self.has_left_sidebar(context) or bool(main_reg)
     context['has_left_sidebar'] = has_sidebar
     context['content_div_css'] = self.get_conditional_css_classes(
         'content', has_sidebar)
     context['breadcrumb_div_css'] = self.get_conditional_css_classes(
         'breadcrumbs', has_sidebar)
     context['has_banner'] = self.has_conf_banner(current_site)
     context['primary_branding_color'] = self.primary_branding_color
     context['secondary_branding_color'] = self.secondary_branding_color
     context['conference_logo'] = self.conference_logo
     context['conference_title'] = self.title
     context['has_social_media'] = self.has_social_media
     context['main_registration'] = main_reg
     context['sponsors'] = self.sponsors.all()
     context['organizers'] = self.organizers.all()
     context['secondary_registration'] = self.sub_registration.all()
     context[
         'secondary_registration_heading'] = self.secondary_registration_heading
     context[
         'secondary_registration_description'] = self.secondary_registration_description
     context['home'] = self.relative_url(current_site)
     return context
Ejemplo n.º 23
0
 def test_port_in_http_host_header_is_ignored(self):
     # port in the HTTP_HOST header is ignored
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = "%s:%s" % (self.events_site.hostname, self.events_site.port)
     request.META['SERVER_PORT'] = self.alternate_port_events_site.port
     self.assertEqual(Site.find_for_request(request), self.alternate_port_events_site)
Ejemplo n.º 24
0
 def test_unrecognised_host_header_routes_to_default_site(self):
     # requests with an unrecognised Host: header should be directed to the default site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.unrecognised_hostname
     request.META['SERVER_PORT'] = '80'
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 25
0
 def test_ports_in_request_headers_are_respected(self):
     # ports in the Host: header should be respected
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.alternate_port_events_site.hostname
     request.META['SERVER_PORT'] = self.alternate_port_events_site.port
     self.assertEqual(Site.find_for_request(request), self.alternate_port_events_site)
Ejemplo n.º 26
0
 def test_valid_headers_route_to_specific_site(self):
     # requests with a known Host: header should be directed to the specific site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.events_site.hostname
     request.META['SERVER_PORT'] = self.events_site.port
     self.assertEqual(Site.find_for_request(request), self.events_site)
Ejemplo n.º 27
0
 def test_ports_in_request_headers_are_respected(self):
     # ports in the Host: header should be respected
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.alternate_port_events_site.hostname
     request.META['SERVER_PORT'] = self.alternate_port_events_site.port
     self.assertEqual(Site.find_for_request(request), self.alternate_port_events_site)
Ejemplo n.º 28
0
 def test_unrecognised_host_header_routes_to_default_site(self):
     # requests with an unrecognised Host: header should be directed to the default site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.unrecognised_hostname
     request.META['SERVER_PORT'] = '80'
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 29
0
 def test_unrecognised_port_and_default_host_routes_to_default_site(self):
     # requests to the default host on an unrecognised port should be directed to the default site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.default_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 30
0
 def test_unrecognised_port_and_default_host_routes_to_default_site(self):
     # requests to the default host on an unrecognised port should be directed to the default site
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.default_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 31
0
    def get_context(self, request):
        context = super(ConferenceSubPage, self).get_context(request)
        current_site = Site.find_for_request(request)
        parent = self.get_parent_of_type('conference page')
        has_sidebar = parent.has_left_sidebar(context) or bool(main_reg)

        # Set social media fields dynamically and
        # get all the values from the parent page.
        # This doesn't seem like a good practice
        # How else can this be done?
        social_media_fields = [f.name for f in SocialMediaFields._meta.get_fields()]
        for field in social_media_fields:
            exec('self.' + field + ' = ' + 'parent.' + field)

        context['primary_branding_color'] = parent.primary_branding_color
        context['secondary_branding_color'] = parent.secondary_branding_color
        context['conference_logo'] = parent.conference_logo 
        context['conference_title'] = parent.title
        context['has_social_media'] = parent.has_social_media
        context['main_registration'] = parent.main_registration.all()
        context['sponsors'] = parent.sponsors.all()
        context['organizers'] = parent.organizers.all()
        context['secondary_registration'] = parent.sub_registration.all()
        context['secondary_registration_heading'] = parent.secondary_registration_heading
        context['secondary_registration_description'] = parent.secondary_registration_description
        context['home'] = parent.relative_url(current_site)
        return context
Ejemplo n.º 32
0
def get_root_page() -> Page:
    try:
        return Page.objects.get(depth=1)
    except Page.MultipleObjectsReturned:
        # Reraise MultipleObjectsReturned, but with our own message
        raise Site.MultipleObjectsReturned(
            'Foliage can\'t auto-determine the root page. '
            'More than one Page exists with depth 1 in the database!')
Ejemplo n.º 33
0
 def test_unrecognised_port_on_known_hostname_routes_there_if_no_ambiguity(self):
     # requests on an unrecognised port should be directed to the site with
     # matching hostname if there is no ambiguity
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.about_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.about_site)
Ejemplo n.º 34
0
def get_site() -> Site:
    try:
        return Site.objects.get()
    except Site.MultipleObjectsReturned:
        # Reraise MultipleObjectsReturned, but with our own message
        raise Site.MultipleObjectsReturned(
            'Foliage can\'t auto-determine the Wagtail Site. '
            'More than one Site exists in the database!')
Ejemplo n.º 35
0
 def _import_pages(self, exported_page_data):
     # Delete any existing pages.
     for page in Page.objects.all():
         page.delete()
     with open(exported_page_data, 'r') as fh:
         page_data = cPickle.load(fh)
     for page_name, info in page_data.items():
         self.logger.debug('Creating page {}'.format(page_name))
         page = info['class'](**info['kwargs'])
         page.save()
         self._pages[page_name] = page
     # Add a Wagtail Site, or nothing will appear anywhere.
     home_page = HomePage.objects.all()[0]
     site = Site(hostname='localhost',
                 root_page=home_page,
                 is_default_site=True)
     site.save()
Ejemplo n.º 36
0
 def __call__(self, request, *args, **kwargs):
     self.request = request
     self.site = Site.find_for_request(self.request)
     self.identity = IdentitySettings.for_site(self.site)
     self.meta = Metadata(request=request,
                          site=self.site,
                          page=kwargs.get('page', None))
     return super().__call__(request, *args, **kwargs)
Ejemplo n.º 37
0
 def test_unrecognised_port_on_known_hostname_routes_there_if_no_ambiguity(self):
     # requests on an unrecognised port should be directed to the site with
     # matching hostname if there is no ambiguity
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.about_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.about_site)
Ejemplo n.º 38
0
    def setUp(self):
        self.home_page = Page.objects.get(id=2)
        self.routable_page = self.home_page.add_child(instance=RoutablePageTest(title="Routable Page", live=True))

        self.rf = RequestFactory()
        self.request = self.rf.get(self.routable_page.url)
        self.request.site = Site.find_for_request(self.request)
        self.context = {"request": self.request}
Ejemplo n.º 39
0
 def test_unrecognised_port_on_known_hostname_routes_to_default_site_if_ambiguity(self):
     # requests on an unrecognised port should be directed to the default
     # site, even if their hostname (but not port) matches more than one
     # other entry
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.events_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 40
0
 def process_request(self, request):
     """
     Set request.site to contain the Site object responsible for handling this request,
     according to hostname matching rules
     """
     try:
         request.site = Site.find_for_request(request)
     except Site.DoesNotExist:
         request.site = None
Ejemplo n.º 41
0
    def test_get(self, rf, languages, sites):
        site = sites.get(hostname='es.localhost')

        request = HttpRequest()
        request.path = '/'
        request.META['HTTP_HOST'] = 'es.localhost'
        request.META['SERVER_PORT'] = 8000

        assert Site.find_for_request(request) == site
Ejemplo n.º 42
0
 def process_request(self, request):
     """
     Set request.site to contain the Site object responsible for handling this request,
     according to hostname matching rules
     """
     try:
         request.site = Site.find_for_request(request)
     except Site.DoesNotExist:
         request.site = None
Ejemplo n.º 43
0
 def test_unrecognised_port_on_known_hostname_routes_to_default_site_if_ambiguity(self):
     # requests on an unrecognised port should be directed to the default
     # site, even if their hostname (but not port) matches more than one
     # other entry
     request = HttpRequest()
     request.path = '/'
     request.META['HTTP_HOST'] = self.events_site.hostname
     request.META['SERVER_PORT'] = self.unrecognised_port
     self.assertEqual(Site.find_for_request(request), self.default_site)
Ejemplo n.º 44
0
 def item_enclosure_url(self, item):
     if not getattr(item.featured_image, 'file', None):
         url = item.featured_image
     else:
         url = item.featured_image.file.url
         url = "{0}://{1}{2}".format(
             "http" + ("s" if self.request.is_secure() else ""),
             Site.find_for_request(self.request).hostname, url)
     return url
Ejemplo n.º 45
0
    def test_tag(self):
        factory = RequestFactory()

        request = factory.get('/home/blog/tag/news/')
        request.site = Site.find_for_request(request)
        request.user = User.objects.create_user(username='******')

        response = self.bip.tag(request)
        self.assertEqual(200, response.status_code)
Ejemplo n.º 46
0
    def get_context(self, request):
        context = super(FotoalbumIndexPage, self).get_context(request)
        this_site = Site.find_for_request(request)

        tags = FotoalbumTag.objects.all()

        context['tags'] = tags

        return context
Ejemplo n.º 47
0
    def test_tag(self):
        factory = RequestFactory()

        request = factory.get('/home/blog/tag/news/')
        request.site = Site.find_for_request(request)
        request.user = User.objects.create_user(username='******')

        response = self.bip.tag(request)
        self.assertEqual(200, response.status_code)
Ejemplo n.º 48
0
def run_scan(request):
    site = Site.find_for_request(request)
    celery_status = get_celery_worker_status()
    if 'ERROR' not in celery_status:
        broken_link_scan(site)
    else:
        messages.warning(request, _('No celery workers are running, the scan was not conducted.'))

    return redirect('wagtaillinkchecker')
Ejemplo n.º 49
0
 def get_url(self, obj):
     root_path = Site.get_site_root_paths()
     if len(root_path):
         root_path = root_path[0][1]
         if obj.url_path == root_path:
             return '/'
         elif root_path in obj.url_path:
             if obj.url_path.index(root_path) == 0:
                 return obj.url.replace(root_path, '/', 1)
     return obj.url_path
Ejemplo n.º 50
0
 def item_enclosure_url(self, item):
     if not getattr(item.featured_image, 'file', None):
         url = item.featured_image
     else:
         url = item.featured_image.file.url
         url = "{0}://{1}{2}".format(
             "http" + ("s" if self.request.is_secure() else ""),
             Site.find_for_request(self.request).hostname,
             url
         )
     return url
Ejemplo n.º 51
0
    def setUp(self):
        self.home_page = Page.objects.get(id=2)
        self.routable_page = self.home_page.add_child(instance=NewStyleRoutablePageTest(
            title="Routable Page",
            slug='routable-page',
            live=True,
        ))

        self.rf = RequestFactory()
        self.request = self.rf.get(self.routable_page.url)
        self.request.site = Site.find_for_request(self.request)
        self.context = {'request': self.request}
Ejemplo n.º 52
0
    def test_find_site_for_request(self):
        default_site = Site.objects.get(is_default_site=True)
        events_page = Page.objects.get(url_path='/home/events/')
        events_site = Site.objects.create(hostname='events.example.com', root_page=events_page)

        # requests without a Host: header should be directed to the default site
        request = HttpRequest()
        request.path = '/'
        self.assertEqual(Site.find_for_request(request), default_site)

        # requests with a known Host: header should be directed to the specific site
        request = HttpRequest()
        request.path = '/'
        request.META['HTTP_HOST'] = 'events.example.com'
        self.assertEqual(Site.find_for_request(request), events_site)

        # requests with an unrecognised Host: header should be directed to the default site
        request = HttpRequest()
        request.path = '/'
        request.META['HTTP_HOST'] = 'unknown.example.com'
        self.assertEqual(Site.find_for_request(request), default_site)
Ejemplo n.º 53
0
def index(request):
    instance = SitePreferences.objects.filter(site=Site.find_for_request(request)).first()
    form = SitePreferencesForm(instance=instance)
    EditHandler = get_edit_handler(SitePreferences)

    if request.method == "POST":
        instance = SitePreferences.objects.filter(site=Site.find_for_request(request)).first()
        form = SitePreferencesForm(request.POST, instance=instance)
        if form.is_valid():
            edit_handler = EditHandler(instance=SitePreferences, form=form)
            form.save()
            messages.success(request, 'The form has been successfully saved.')
            return redirect('wagtaillinkchecker')
        else:
            messages.error(request, 'The form could not be saved due to validation errors')
    else:
        form = SitePreferencesForm(instance=instance)
        edit_handler = EditHandler(instance=SitePreferences, form=form)

    return render(request, 'wagtaillinkchecker/index.html', {
        'form': form,
        'edit_handler': edit_handler,
    })
Ejemplo n.º 54
0
def flag_enabled(key):
    request = get_request()
    site = Site.find_for_request(request)
    state_for_site = site.flagstate_set.filter(flag_id=key, \
            ).first()
    if state_for_site is not None:
        return state_for_site.enabled

    else:
        try:
            flag = Flag.objects.get(pk=key)
            return flag.enabled_by_default
        except ObjectDoesNotExist:
            return False
Ejemplo n.º 55
0
    def get_context(self, request):
        context = super(BasePageWithoutStaffPageForeignKeys, self).get_context(request)

        context['breadcrumbs'] = get_breadcrumbs(self)

        context['sidebartitle'] = 'Browse this Section'
        if self.specific_class.get_verbose_name() == 'Intranet Units Page':
            for p in list(reversed(self.get_ancestors(True))):
                try:
                    if p.specific.start_sidebar_from_here:
                        context['sidebartitle'] = p.title
                        break
                except:
                    pass
                
        # JEJ- fix this later to remove logic from the template.
        current_site = Site.find_for_request(request)
        sidebar = [] 
        if self.show_sidebar:
            ancestors = self.get_ancestors(True).specific()
            a = len(ancestors) - 1
            while a > 0:
                sidebar_parent = ancestors[a]
                if sidebar_parent.start_sidebar_from_here:
                    break
                a = a - 1

            children = sidebar_parent.get_children().in_menu().live().specific()
            for child in children:
                new_child = {
                    'title': child.title,
                    'url': child.relative_url(current_site),
                    'children': []
                }
                grandchildren = child.get_children().in_menu().live().specific()
                for grandchild in grandchildren:
                    new_child['children'].append({
                        'title': grandchild.title,
                        'url': grandchild.relative_url(current_site),
                        'children': [],
                    })

                sidebar.append(new_child)
        context['sidebar'] = sidebar
        
        return context
Ejemplo n.º 56
0
    def get_hours_page(self, request):
        """
        Get a link to the hours page from the ID set
        in the base config file.

        Args:
            request, object

        Return:
            String, url. 
        """
        try:
            current_site = Site.find_for_request(request)
            return Page.objects.get(id=HOURS_PAGE).relative_url(current_site)
        except(IndexError) as e:
            msg = 'HOURS_PAGE in settings.base is configured incorrectly. \
Either it is set to the ID of a non-existing page or it has an incorrect value.'
            raise IndexError(msg)
Ejemplo n.º 57
0
    def get_url_parts(self):
        root_paths = set(Site.get_site_root_paths())
        test_site_paths = set([x for x in root_paths if 'test' in Site.objects.get(id=x[0]).site_name.lower()])
        prod_site_paths = root_paths - test_site_paths
        if False and self.content_type.app_label == 'kehmet':
            root_paths = test_site_paths
        else:
            root_paths = prod_site_paths

        for (site_id, root_path, root_url) in root_paths:
            if self.url_path.startswith(root_path):
                page_path = reverse('wagtail_serve', args=(self.url_path[len(root_path):],))

                # Remove the trailing slash from the URL reverse generates if
                # WAGTAIL_APPEND_SLASH is False and we're not trying to serve
                # the root path
                if not WAGTAIL_APPEND_SLASH and page_path != '/':
                    page_path = page_path.rstrip('/')

                return (site_id, root_url, page_path)
Ejemplo n.º 58
0
    def get_context(self, request):
        """
        Override the page object's get context method.
        """
        context = super(StandardPage, self).get_context(request)
        current_site = Site.find_for_request(request) 
        has_featured_lib_expert = self.get_featured_lib_expert()[0]

        if has_featured_lib_expert:
            lib_expert_block = self.unpack_lib_expert_block(self.get_featured_lib_expert()[1], current_site)
            context['has_featured_lib_expert'] = has_featured_lib_expert
            context['featured_lib_expert'] = self.get_featured_lib_expert()[1]
            context['featured_lib_expert_name'] = lib_expert_block['person'] 
            context['featured_lib_expert_image'] = lib_expert_block['image']
            context['featured_lib_expert_profile'] = lib_expert_block['profile'] 
            context['featured_lib_expert_links'] = lib_expert_block['links']

        context['has_search_widget'] = self.enable_search_widget

        return context
Ejemplo n.º 59
0
 def get_context(self, request):
     context = super(ConferencePage, self).get_context(request)
     current_site = Site.find_for_request(request)
     main_reg = self.main_registration.all()
     has_sidebar = self.has_left_sidebar(context) or bool(main_reg)
     context['has_left_sidebar'] = has_sidebar
     context['content_div_css'] = self.get_conditional_css_classes('content', has_sidebar)
     context['breadcrumb_div_css'] = self.get_conditional_css_classes('breadcrumbs', has_sidebar)
     context['has_banner'] = self.has_conf_banner(current_site)
     context['primary_branding_color'] = self.primary_branding_color
     context['secondary_branding_color'] = self.secondary_branding_color
     context['conference_logo'] = self.conference_logo
     context['conference_title'] = self.title
     context['has_social_media'] = self.has_social_media
     context['main_registration'] = main_reg
     context['sponsors'] = self.sponsors.all()
     context['organizers'] = self.organizers.all()
     context['secondary_registration'] = self.sub_registration.all()
     context['secondary_registration_heading'] = self.secondary_registration_heading
     context['secondary_registration_description'] = self.secondary_registration_description
     context['home'] = self.relative_url(current_site)
     return context
Ejemplo n.º 60
0
    def get_related_collections(self, request):
        """
        Get the related collections for a web exhibit.
    
        Args:
            request: object

        Returns:
            A list of tuples where the first item in 
            the tuple is a collection title and the
            second item is a url. If no related 
            collections are found, returns None.
        """
        current_site = Site.find_for_request(request)
        collections = self.exhibit_page_related_collection_placement.all() 
        related_collections = '<ul>'
        if collections:
            for collection in collections:
                if collection.related_collection:
                    related_collections += '<li><a href="' + collection.related_collection.relative_url(current_site) + '">' + collection.related_collection.title + '</a></li>'
            return related_collections + '</ul>'
        return None