Beispiel #1
0
class FlatpageModelTests(SimpleTestCase):
    def setUp(self):
        self.page = FlatPage(title='Café!', url='/café/')

    def test_get_absolute_url_urlencodes(self):
        self.assertEqual(self.page.get_absolute_url(), '/caf%C3%A9/')

    @override_script_prefix('/prefix/')
    def test_get_absolute_url_honors_script_prefix(self):
        self.assertEqual(self.page.get_absolute_url(), '/prefix/caf%C3%A9/')

    def test_str(self):
        self.assertEqual(str(self.page), '/café/ -- Café!')

    @override_settings(ROOT_URLCONF='flatpages_tests.urls')
    def test_get_absolute_url_include(self):
        self.assertEqual(self.page.get_absolute_url(),
                         '/flatpage_root/caf%C3%A9/')

    @override_settings(ROOT_URLCONF='flatpages_tests.no_slash_urls')
    def test_get_absolute_url_include_no_slash(self):
        self.assertEqual(self.page.get_absolute_url(), '/flatpagecaf%C3%A9/')

    @override_settings(ROOT_URLCONF='flatpages_tests.absolute_urls')
    def test_get_absolute_url_with_hardcoded_url(self):
        fp = FlatPage(title='Test', url='/hardcoded/')
        self.assertEqual(fp.get_absolute_url(), '/flatpage/')
Beispiel #2
0
class FlatpageModelTests(SimpleTestCase):
    def setUp(self):
        self.page = FlatPage(title="Café!", url="/café/")

    def test_get_absolute_url_urlencodes(self):
        self.assertEqual(self.page.get_absolute_url(), "/caf%C3%A9/")

    @override_script_prefix("/prefix/")
    def test_get_absolute_url_honors_script_prefix(self):
        self.assertEqual(self.page.get_absolute_url(), "/prefix/caf%C3%A9/")

    def test_str(self):
        self.assertEqual(str(self.page), "/café/ -- Café!")

    @override_settings(ROOT_URLCONF="flatpages_tests.urls")
    def test_get_absolute_url_include(self):
        self.assertEqual(self.page.get_absolute_url(),
                         "/flatpage_root/caf%C3%A9/")

    @override_settings(ROOT_URLCONF="flatpages_tests.no_slash_urls")
    def test_get_absolute_url_include_no_slash(self):
        self.assertEqual(self.page.get_absolute_url(), "/flatpagecaf%C3%A9/")

    @override_settings(ROOT_URLCONF="flatpages_tests.absolute_urls")
    def test_get_absolute_url_with_hardcoded_url(self):
        fp = FlatPage(title="Test", url="/hardcoded/")
        self.assertEqual(fp.get_absolute_url(), "/flatpage/")
Beispiel #3
0
 def test_get_absolute_url_honors_script_prefix(self):
     pf = FlatPage(title="Tea!", url='/tea/')
     set_script_prefix('/beverages/')
     try:
         self.assertEqual(pf.get_absolute_url(), '/beverages/tea/')
     finally:
         clear_script_prefix()
 def test_get_absolute_url_honors_script_prefix(self):
     pf = FlatPage(title="Tea!", url='/tea/')
     set_script_prefix('/beverages/')
     try:
         self.assertEqual(pf.get_absolute_url(), '/beverages/tea/')
     finally:
         clear_script_prefix()
Beispiel #5
0
    def test_create_flat_page(self):
        # Create flat page
        page = FlatPage()
        page.url = '/about/'
        page.title = 'About me'
        page.content = 'All about me'
        page.save()

        # Add the site
        page.sites.add(Site.objects.all()[0])
        page.save()

        # Check new page saved
        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEquals(only_page, page)

        # Check data correct
        self.assertEquals(only_page.url, '/about/')
        self.assertEquals(only_page.title, 'About me')
        self.assertEquals(only_page.content, 'All about me')

        # Get URL
        page_url = str(only_page.get_absolute_url())

        # Get the page
        response = self.client.get(page_url)
        self.assertEquals(response.status_code, 200)

        # Check title and content in response
        self.assertTrue('About me' in response.content)
        self.assertTrue('All about me' in response.content)
Beispiel #6
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about/'
        page.title = 'about me'
        page.content = 'something about me'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages), 1)
        self.assertEqual(all_pages[0], page)

        p = all_pages[0]
        self.assertEquals(p.url, page.url)
        self.assertEquals(p.title, page.title)
        self.assertEquals(p.content, page.content)

        p_url = p.get_absolute_url()

        r = self.client.get(p_url)
        self.assertEquals(r.status_code, 200)
        self.assertTrue(page.title in r.content)
        self.assertTrue(page.content in r.content)
Beispiel #7
0
def startpage(request):
    page = FlatPage.objects.filter(url="/")
    if page:
        page = page[0]
    else:
        page = FlatPage("/", "Welcome", "<h1>Hello World!</h1>")
        page.save()
    news = News.active_objects.all()[:5]
    return render_to_response('news/startpage.html',  {"latest_news": news,
                                                       "start_title": page.title, 
                                                       "content": page.content}, 
                              context_instance=RequestContext(request))
Beispiel #8
0
def fallback_page(slug):
    md = LIB / f'{slug}.md'
    html = LIB / f'{slug}.html'
    if html.exists():
        data = open(html).read()
        return FlatPage(content=data, title=slug, template_name='flatpages/html.html')
    elif md.exists():
        data = open(md).read()
        return FlatPage(content=data, title=slug, template_name='flatpages/markdown.html')
    else:
        data = _('Page {slug} not found').format(slug=slug)
        return FlatPage(content=data, title=slug, template_name='flatpages/html.html')
def newpage(request, url):
    """
    New Flat page wiki view.

    template hardcoded for now
    """

    if not request.user.is_authenticated():
        raise Http404
    
    from urlparse import urlparse
    # if referer then use it or default '/'
    ref = urlparse(request.META.get('HTTP_REFERER', ''))[2]
    # use hidden field if it's there
    ref = request.REQUEST.get('ref', ref)
    if ref == '':
        ref = '/'

    #return render_to_response(DEFAULT_TEMPLATE_NEW,  
    #    RequestContext( request, { 'url': url, 'ref': ref } ))
    
    if request.method == 'POST':
        if request.POST['result'] == 'Cancel':
            return HttpResponseRedirect(ref)
        else:
            form = WikiPageForm(request.POST)
            if form.is_valid():
                try:
                    f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
                except Http404:
                    f = FlatPage()
                    f.url = str(form.clean()['url'])
                    f.title = form.clean()['title']
                    f.content = str(form.clean()['content'])
                    f.enable_comments = False
                    f.registration_required = False
                    f.save()
                    # need to save get a pk before adding a M2M
                    s = Site.objects.get_current()
                    f.sites.add(s)
                    f.save()
                    return HttpResponseRedirect(f.url)

    else:
        form = WikiPageForm({'url': url, })
        form.ignore_errors = True
        #form.errors().clear()

    response = render_to_response(DEFAULT_TEMPLATE_NEW,  
        RequestContext( request, { 'form': form, 'ref': ref }) )
    #populate_xheaders(request, response, FlatPage, f.id)
    return response
class FlatpageModelTests(SimpleTestCase):
    def setUp(self):
        self.page = FlatPage(title='Café!', url='/café/')

    def test_get_absolute_url_urlencodes(self):
        self.assertEqual(self.page.get_absolute_url(), '/caf%C3%A9/')

    @override_script_prefix('/prefix/')
    def test_get_absolute_url_honors_script_prefix(self):
        self.assertEqual(self.page.get_absolute_url(), '/prefix/caf%C3%A9/')

    def test_str(self):
        self.assertEqual(str(self.page), '/café/ -- Café!')
Beispiel #11
0
    def test_create_flat_page(self):
        # create a flat page
        page = FlatPage()
        page.url = '/about/'
        page.title = 'About me'
        page.content = 'All about me'
        page.save()
        page.sites.add(Site.objects.all()[0])
        page.save()

        # check the new page is saved
        all_pages = FlatPage.objects.all()
        self.assertEqual(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEqual(only_page, page)

        # check the data of the page
        self.assertEquals(only_page.url, page.url)
        self.assertEquals(only_page.title, page.title)
        self.assertEquals(only_page.content, page.content)

        # check the page url
        page_url = only_page.get_absolute_url()
        response = self.client.get(page_url)
        self.assertEquals(response.status_code, 200)
Beispiel #12
0
    def test_create_flat_page(self):
        # create flat page
        page = FlatPage()
        page.url = '/about/'
        page.title = 'About me'
        page.content = 'All about me'
        page.save()

        # add the site
        page.sites.add(Site.objects.all()[0])
        page.save()

        # check new page saved
        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages),1)
        only_page = all_pages[0]
        self.assertEquals(only_page, page)

        # check data correct
        self.assertEquals(only_page.url, '/about/')
        self.assertEquals(only_page.title, 'About me')
        self.assertEquals(only_page.content, 'All about me')

        # get url
        page_url = str(only_page.get_absolute_url())

        # get the page
        response = self.client.get(page_url)
        self.assertEquals(response.status_code, 200)

        # check title and content in response
        self.assertTrue('About me' in response.content)
        self.assertTrue('All about me' in response.content)
Beispiel #13
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about/'
        page.title = 'about me'
        page.content = 'something about me'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages),1)
        self.assertEqual(all_pages[0],page)

        p = all_pages[0]
        self.assertEquals(p.url,page.url)
        self.assertEquals(p.title,page.title)
        self.assertEquals(p.content,page.content)

        p_url = p.get_absolute_url()

        r = self.client.get(p_url)
        self.assertEquals(r.status_code,200)
        self.assertTrue(page.title in r.content)
        self.assertTrue(page.content in r.content)
Beispiel #14
0
    def test_create_flat_page(self):
        # Create flat page
        page = FlatPage()
        page.url = "/about/"
        page.title = "About me"
        page.content = "All about me"
        page.save()

        # Add the site
        page.sites.add(Site.objects.all()[0])
        page.save()

        # Check new page saved
        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEquals(only_page, page)

        # Check data correct
        self.assertEquals(only_page.url, "/about/")
        self.assertEquals(only_page.title, "About me")
        self.assertEquals(only_page.content, "All about me")

        # Get URL
        page_url = str(only_page.get_absolute_url())

        # Get the page
        response = self.client.get(page_url)
        self.assertEquals(response.status_code, 200)

        # Check title and content in response
        self.assertTrue("About me" in response.content)
        self.assertTrue("All about me" in response.content)
Beispiel #15
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about'
        page.title = 'About me'
        page.content = "All about me"
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_pages = FlatPage.objects.all()
        self.assertEqual(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEqual(only_page, page)

        self.assertEquals(only_page.url, '/about')
        self.assertEquals(only_page.title, 'About me')
        self.assertEquals(only_page.content, 'All about me')

        page_url = reverse(
            'django.contrib.flatpages.views.flatpage',
            kwargs={'url': 'about'}
        )

        response = self.client.get(page_url)
        self.assertEqual(response.status_code, 200)

        self.assertTrue('About me' in response.content)
        self.assertTrue('All about me' in response.content)
Beispiel #16
0
    def test_create_flat_page(self):

        page = FlatPage()
        page.url = '/about/'
        page.title = 'About me'
        page.content = 'All about me'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_pages = FlatPage.objects.all()
        self.assertEquals(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEquals(only_page, page)

        self.assertEquals(only_page.url, '/about/')
        self.assertEquals(only_page.title, 'About me')
        self.assertEquals(only_page.content, 'All about me')

        page_url = only_page.get_absolute_url()

        response = self.client.get(page_url)
        self.assertEquals(response.status_code, 200)

        self.assertTrue('About me' in response.content)
        self.assertTrue('All about me' in response.content)
Beispiel #17
0
def create_about_page(app, created_models, verbosity, **kwargs):
    from django.contrib.flatpages.models import FlatPage
    from django.contrib.sites.models import Site
    if FlatPage not in created_models:
        return
    if FlatPage.objects.count():
        return
    text = '''Hello, I'm default about page.

Please change me in admin. I'm also known as FlatPage.'''
    about = FlatPage(url='/about/', title='About', content=text,
                     enable_comments=False, registration_required=False)
    about.save()
    about.sites.add(*Site.objects.all())
Beispiel #18
0
 def test_flatpages(self):
     f = FlatPage()
     f.url = "/about/"
     f.title = "About page"
     f.content = "<p>About</p>"
     f.save()
     s = Site.objects.all()[0]
     f.sites.add(s)
     f.save()
     client = Client()
     response = client.get('/about/')
     self.assertEqual(response.status_code, 200)
Beispiel #19
0
 def test_foreignkey_dict(self):
     FK_REGISTRY = {
         'flatpages.flatpage': {'name': 'category'}
     }
     _process_registry(FK_REGISTRY, register_fk)
     from django.contrib.flatpages.models import FlatPage
     self.assertTrue('category' in FlatPage()._meta.get_all_field_names())
Beispiel #20
0
def flatpages(db):
    from django.contrib.flatpages.models import FlatPage

    return FlatPage.objects.bulk_create([
        FlatPage(pk=pk, title=random_string(50), url=random_string(50))
        for pk in range(1)
    ])
    def test_foreignkey_dict(self):
        FK_REGISTRY = {"flatpages.flatpage": {"name": "category"}}
        _process_registry(FK_REGISTRY, registry.register_fk)
        from django.contrib.flatpages.models import FlatPage

        self.assertTrue(
            "category" in [f.name for f in FlatPage()._meta.get_fields()])
        def test_new_foreignkey_string(self):
            registry.register_model("flatpages", "flatpage", "ForeignKey",
                                    "category")
            from django.contrib.flatpages.models import FlatPage

            self.assertTrue(
                "category" in [f.name for f in FlatPage()._meta.get_fields()])
    def test_m2m_string(self):
        M2M_REGISTRY = {"flatpages.flatpage": "categories"}
        _process_registry(M2M_REGISTRY, registry.register_m2m)
        from django.contrib.flatpages.models import FlatPage

        self.assertTrue(
            "category" in [f.name for f in FlatPage()._meta.get_fields()])
Beispiel #24
0
def create_about_page(app, created_models, verbosity, **kwargs):
    from django.contrib.flatpages.models import FlatPage
    from django.contrib.sites.models import Site
    if FlatPage not in created_models:
        return
    if FlatPage.objects.count():
        return
    text = '''Hello, I'm default about page.

Please change me in admin. I'm also known as FlatPage.'''
    about = FlatPage(url='/about/',
                     title='About',
                     content=text,
                     enable_comments=False,
                     registration_required=False)
    about.save()
    about.sites.add(*Site.objects.all())
Beispiel #25
0
def flatpage(request, url):
    """
    Extended editable flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not request.GET.get('action') in ('create', 'edit', 'delete'):
        return flatpage_detail(request, url)
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_none(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
    if not f:
        if not request.user.has_perm('flatpages.add_flatpage'):
            raise Http404
        f = FlatPage(url=url)
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f and f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if request.method == 'POST':
        form = FlatPageEditForm(request.POST, instance=f)
        if form.is_valid(): # All validation rules pass
            f.save()
            current_site = Site.objects.get_current()
            if not current_site in f.sites.all():
                # Assign page to current site
                f.sites.add(current_site)
                f.save()
            msg = _("The %(verbose_name)s was updated successfully.") %\
                {"verbose_name": FlatPage._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return HttpResponseRedirect(f.url)
    else:
        if request.GET.get('action') == 'delete':
            f.delete()
            msg = _("The %(verbose_name)s was deleted.") %\
                {"verbose_name": FlatPage._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return HttpResponseRedirect('/')
        form = FlatPageEditForm(instance=f)
    if f.template_name:
        t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    c = RequestContext(request, {
        'form': form,
        'flatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
    def handle(self, *args, **options):

        try:
            site = Site.objects.get()
        except Site.DoesNotExist:
            site = Site()
        if args:
            if len(args) > 1:
                raise CommandError('Command accept at most one parameter.')
            site.domain = args[0]
            site.name = args[0]
        else:
            hostname = get_host_name()
            site.domain = hostname
            site.name = hostname
        site.save()

        try:
            page = FlatPage.objects.get(url='/getting-started/')
            page.sites = [site]
            page.save()
        except FlatPage.DoesNotExist:
            page = FlatPage(url='/getting-started/', title='Getting Started', registration_required=False)
            page.content = 'Go to admin panel to change welcome message!'
            page.save()
            page.sites = [site]
            page.save()
def flatpage_with_fallback(slug):
    md = LIB / f"{slug}.md"
    html = LIB / f"{slug}.html"
    if html.exists():
        data = open(html).read()
        return FlatPage(content=data,
                        title=slug,
                        template_name="flatpages/html.html")
    elif md.exists():
        data = open(md).read()
        return FlatPage(content=data,
                        title=slug,
                        template_name="flatpages/markdown.html")
    else:
        data = _("Page {slug} not found").format(slug=slug)
        return FlatPage(content=data,
                        title=slug,
                        template_name="flatpages/html.html")
Beispiel #28
0
    def html_to_flatpage(self):
        """
        Prevede prelozene, zkompilovane HTML stranky do Flatpage:

        * prevedene do naseho layoutu
        * URL vedouci na nase preklady (pokud existuji); v opacnem pripade
          smeruji na oficialni dokumentaci
        * prelozene posledni zbytky anglickych fragmentu v tele stranky
        """
        translated_urls = [i.get_absolute_url() for i in super(TranslationManager, self).all()]
        for obj in super(TranslationManager, self).all():
            # tady se deje vse podstatne:
            dhp = DocHtmlProcessor(obj.source_html_content, obj.html_id.replace('/', '-'))
            title, _content, sidebar = dhp.process(translated_urls)
            context = {
                'content': _content,
                'sidebar': sidebar,
                'translation': obj
            }
            content = render_to_string(self.DOC_CONTENT_TEMPLATE, context)
            fp = FlatPage.objects.filter(url=obj.get_absolute_url())
            if fp.count():
                # dokumentace j*z v podobe FlatPage existuje
                # aktualizujeme ji...
                fp = fp[0]
                fp.title = title
                fp.content = content
                fp.save()
            else:
                # dokumentace v podobe FlatPage neexistuje
                # vytvorime ji...
                fp = FlatPage(
                    url = obj.get_absolute_url(),
                    title = title,
                    content = content,
                    enable_comments = False,
                    registration_required = False
                )
                fp.save()
                site = Site.objects.get_current()
                fp.sites.add(site)
            obj.flat_page = fp
            obj.save()
Beispiel #29
0
    def get(self, request, url):
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'

        from django.contrib.flatpages.views import flatpage, render_flatpage

        if not request.user.is_superuser or FlatPage.objects.filter(url='url', sites=settings.SITE_ID).exists():
            return flatpage(request, url)
        else:
            f = FlatPage(url=url)
            return render_flatpage(request, f)
Beispiel #30
0
 def test_foreignkey_list(self):
     FK_REGISTRY = {
         'flatpages.flatpage': ({
             'name': 'category',
             'related_name': 'cats'
         }, )
     }
     _process_registry(FK_REGISTRY, registry.register_fk)
     from django.contrib.flatpages.models import FlatPage
     self.assertTrue(
         'category' in [f.name for f in FlatPage()._meta.get_fields()])
Beispiel #31
0
    def test_validate_url_does_not_exist(self):
        validator = URLDoesNotExistValidator()
        self.assertRaises(ValidationError, validator, '/')
        try:
            validator('/invalid/')
        except ValidationError:
            self.fail('URLDoesNotExistValidator raised ValidationError'
                      'unexpectedly!')

        FlatPage(title='test page', url='/test/page/').save()
        self.assertRaises(ValidationError, validator, '/test/page/')
Beispiel #32
0
 def forwards(self, orm):
     """
     not going through the south db orm, but this seems to work anyway
     """
     page_data = [{'url': '/about/',
                   'title': u'About',
                   'content': u'Stub about flatpage',
                   },
                  {'url': '/contact/',
                   'title': 'Contact',
                   'content': u'Stub contact flatpage',
                   },
                  {'url': '/faq/',
                   'title': 'Faq',
                   'content': u'Stub faq flatpage',
                   },
                  {'url': '/press/',
                   'title': 'Press',
                   'content': u'Stub press flatpage',
                   },
                  {'url': '/tools-and-tips/',
                   'title': 'Tools and tips',
                   'content': u'Tools and tips flatpage',
                   },
                  {'url': '/placement-guide/',
                   'title': 'Placement guide',
                   'content': u'Placement guide flatpage',
                   },
                  ]
     # XXX use the first site
     site = Site.objects.all()[0]
     for page in page_data:
         if len(FlatPage.objects.filter(url=page['url'])) == 0:
             flatpage = FlatPage(enable_comments=False,
                                 registration_required=False,
                                 template_name='',
                                 **page)
             flatpage.save()
             flatpage.sites.add(site)
             flatpage.save()
Beispiel #33
0
def flatpage_new(request):
    if request.method == 'POST':
        form = forms.FlatPageEditForm(request.POST, instance=FlatPage())
        if form.is_valid():
            instance = form.save()
            instance.sites.add(settings.SITE_ID)
            instance.save()
            messages.success(request, 'Page created.')
            return redirect('manage:flatpages')
    else:
        form = forms.FlatPageEditForm()
        form.fields['url'].help_text = "for example '/my-page'"
    return render(request, 'manage/flatpage_new.html', {'form': form})
    def render(self, context):
        # if 'request' in context:
        #     site_pk = get_current_site(context['request']).pk
        # else:
        #     site_pk = settings.SITE_ID
        try:
            # flatpage = FlatPage.objects.get(sites__id=site_pk, url=self.url.resolve(context))
            flatpage = FlatPage.objects.get(url=self.url.resolve(context))
        except ObjectDoesNotExist:
            flatpage = FlatPage(url=self.url.resolve(context))

        context[self.context_name] = flatpage
        return ''
 def forwards(self, orm):
     "Write your forwards methods here."
     # Note: Don't use "from appname.models import ModelName". 
     # Use orm.ModelName to refer to models in this application,
     # and orm['appname.ModelName'] for models in other applications.
     s = Site.objects.get(id='1')
     f = FlatPage(url='/data-archiving/', title='Data Archiving', content='(info about data archiving)')
     f.save()
     f.sites.add(s)
     f.save()
Beispiel #36
0
    def test_filmaster_recommends(self):
        """
            Test filmaster recommends
        """

        fp = FlatPage()
        fp.url = "filmaster-recommends"
        fp.title = "Title"
        fp.content = "Lorem ipsum"
        fp.save()

        flp = filmaster_recommends()
        flat_page = flp['flat_page']
        self.failUnlessEqual(flat_page.title, "Title")
        self.failUnlessEqual(flat_page.content, "Lorem ipsum")
Beispiel #37
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about/'
        page.title = 'О компании'
        page.content = 'Страница о компании'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_page = FlatPage.objects.all()
        self.assertEquals(len(all_page), 1)
        only_page = all_page[0]
        self.assertEquals(only_page, page)

        self.assertEquals(only_page.url, '/about/')
        self.assertEquals(only_page.title, 'О компании')
        self.assertEquals(only_page.content, 'Страница о компании')

        page_url = only_page.get_absolute_url()

        response = self.client.get(page_url)
        self.assertContains(response, 'О компании', status_code=200)
        self.assertContains(response, 'Страница о компании')
def getcontent(context, url, default=None):
    url = "%s%s/" % (HIDDEN_PAGE_PREFIX, url)

    try:
        page = FlatPage.objects.get(url=url)
    except FlatPage.DoesNotExist:
        page = FlatPage(url=url, content=default, title=url.strip("/"))
        if default is not None:
            page.save()
            page.sites = Site.objects.all()
            page.save()

    if context.get('user', None) and getattr(context['user'], "is_staff",
                                             False) and page.pk:
        edit_url = reverse("pages-edit", args=[page.pk]) + "?next=" + getattr(
            context.get("request"), "get_full_path", lambda: "")()
        page.content += "<a class='getcontent-edit' href='%s'>Edit</a>" % edit_url

    return mark_safe(page.content)
Beispiel #39
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about/'
        page.title = 'About me'
        page.content = 'Some words about me and this not perfect world'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_pages = FlatPage.objects.all()
        self.assertEqual(len(all_pages), 1)
        only_page = all_pages[0]
        self.assertEqual(only_page, page)

        self.assertEqual(only_page.url, '/about/')
        self.assertEqual(only_page.title, 'About me')
        self.assertEqual(only_page.content, page.content)

        page_url = only_page.get_absolute_url()

        response = self.client.get(page_url)
        self.assertEqual(response.status_code, 200)
def getcontent(context, url, default=None):
    url = "%s%s/" % (HIDDEN_PAGE_PREFIX, url)

    try:
        page = FlatPage.objects.get(url=url)
    except FlatPage.DoesNotExist:
        page = FlatPage(url=url, content=default or "Change Me!", title=url.strip("/"))
        page.save()
        page.sites = Site.objects.all()
        page.save()

    if context.get('user', None) and getattr(context['user'], "is_staff", False) and page.pk:
        edit_url = reverse("pages-edit", args=[page.pk]) + "?next=" + getattr(context.get("request"), "get_full_path", lambda: "")()
        page.content += "<a class='getcontent-edit' href='%s'>Edit</a>" % edit_url

    return mark_safe(page.content)
Beispiel #41
0
def flatpage_new(request):
    if request.method == 'POST':
        form = forms.FlatPageEditForm(request.POST, instance=FlatPage())
        if form.is_valid():
            instance = form.save()
            instance.sites.add(settings.SITE_ID)
            instance.save()
            if instance.url.startswith('sidebar_'):
                __, location, channel_slug = instance.url.split('_', 2)
                channel = Channel.objects.get(slug=channel_slug)
                instance.title = 'Sidebar (%s) %s' % (location, channel.name)
                instance.save()
            messages.success(request, 'Page created.')
            return redirect('manage:flatpages')
    else:
        form = forms.FlatPageEditForm()
        form.fields['url'].help_text = (
            "for example '/my-page' or 'sidebar_top_main' (see below)")
    return render(request, 'manage/flatpage_new.html', {
        'form': form,
        'channels': Channel.objects.all().order_by('slug')
    })
Beispiel #42
0
    def test_create_flat_page(self):
        page = FlatPage()
        page.url = '/about/'
        page.title = 'О компании'
        page.content = 'Страница о компании'
        page.save()

        page.sites.add(Site.objects.all()[0])
        page.save()

        all_page = FlatPage.objects.all()
        self.assertEquals(len(all_page), 1)
        only_page = all_page[0]
        self.assertEquals(only_page, page)

        self.assertEquals(only_page.url, '/about/')
        self.assertEquals(only_page.title, 'О компании')
        self.assertEquals(only_page.content, 'Страница о компании')

        page_url = only_page.get_absolute_url()

        response = self.client.get(page_url)
        self.assertContains(response, 'О компании', status_code=200)
        self.assertContains(response, 'Страница о компании')
Beispiel #43
0
    def test_validate_local_url(self):
        v = ExtendedURLValidator(verify_exists=True)

        try:
            v('/')
        except ValidationError:
            self.fail('ExtendedURLValidator raised ValidationError'
                      'unexpectedly!')

        try:
            v('/?q=test')  # Query strings shouldn't affect validation
        except ValidationError:
            self.fail('ExtendedURLValidator raised ValidationError'
                      'unexpectedly!')

        with self.assertRaises(ValidationError):
            v('/invalid/')

        with self.assertRaises(ValidationError):
            v('/invalid/?q=test')  # Query strings shouldn't affect validation

        try:
            v('products/')
        except ValidationError:
            self.fail('ExtendedURLValidator raised ValidationError'
                      'unexpectedly!')

        with self.assertRaises(ValidationError):
            v('/products')  # Missing the / is bad

        FlatPage(title='test page', url='/test/page/').save()
        try:
            v('/test/page/')
        except ValidationError:
            self.fail('ExtendedURLValidator raises ValidationError'
                      'unexpectedly!')
Beispiel #44
0
def main():
    applicants = read_results()
    flatpages = FlatPage.objects.filter(url=url)
    if len(flatpages)==0:
        flatpage = FlatPage(url=url)
    elif is_forced:
        flatpage = flatpages[0]
    else:
        print "\nError: old flatpage exists.  Use --force to force overwrite."
        quit()

    template = get_template('result/include/applicant_list.html')
    context = Context({'applicants': applicants})
    flatpage.title = u'ประกาศ'
    flatpage.content = template.render(context)
    flatpage.template_name = 'flatpages/result.html'
    flatpage.save()

    print """.....
Done.
The script only created a flatpage at %s for you.  
You'll have to set the title, its sites, 
and edit other part of the page yourself.""" % (url,)
Beispiel #45
0
 def mk_help(self):
     page = FlatPage(title='Help', content="Wisdom", url="/help/")
     page.save()
     for site in Site.objects.all():
         page.sites.add(site)
Beispiel #46
0
 def items(self):
     from django.contrib.flatpages.models import FlatPage
     from django.contrib.sites.models import Site
     current_site = Site.objects.get_current()
     return FlatPage.all().filter('sites = ', current_site)
Beispiel #47
0
<p>
Don't wait until it is too late. It only takes a couple of minutes to add
your Voter ID number. You can also add details of other voters such as your
family members. <br /> <br />
</p>

<p class="text-center">
<a href="/voterreg/epic/new/"><button class="btn btn-large btn-primary"
type="button">Add Voter Information</button></a>
</p>

""")),
]

for (url, title, content) in PAGES:
    fp = FlatPage(url=url, title=title, content=content)
    fp.save()
    fp.sites.add(site)
    print fp

# Save Your Vote is an initiative to ensure that genuine registered Indian
# voters are not disenfranchised and end up unable to vote on election day.
# Most Indian voters know someone who goes to vote on election day only to
# find their name missing from the electoral role. News articles about this
# issue come up every election, however nothing changes.
#
# On the Save Your Vote website, you will be able to add your Voter ID
# information (and that of your family members who are not internet-savvy).
# We will monitor the Chief Election Commissioner's database to ensure that
# your record does not get deleted. In case your record gets deleted, we will
# notify you through Facebook and e-mail so that you can restore it.
Beispiel #48
0
 def test_get_absolute_url_urlencodes(self):
     pf = FlatPage(title="Café!", url='/café/')
     self.assertEqual(pf.get_absolute_url(), '/caf%C3%A9/')
Beispiel #49
0
 def test_get_absolute_url_honors_script_prefix(self):
     pf = FlatPage(title="Tea!", url="/tea/")
     self.assertEqual(pf.get_absolute_url(), "/beverages/tea/")
 def test_m2m_string(self):
     M2M_REGISTRY = {'flatpages.flatpage': 'categories'}
     _process_registry(M2M_REGISTRY, register_m2m)
     from django.contrib.flatpages.models import FlatPage
     self.assertTrue('category' in FlatPage()._meta.get_all_field_names())
 def test_new_foreignkey_string(self):
     registry.register_model('flatpages', 'flatpage', 'ForeignKey',
                             'category')
     from django.contrib.flatpages.models import FlatPage
     self.assertTrue(
         'category' in FlatPage()._meta.get_all_field_names())
Beispiel #52
0
 def setUp(self):
     f = FlatPage(url='/', title='test')
     f.save()
    def update_initial_account_types(self):

        # Updating account types

        arc = AccountType.objects.filter(name="arc").update(
            visible_for_users=False, title="Archive", connection_string="frontier://FrontierArc/", use_in_gt_import=True
        )
        integr = AccountType.objects.filter(name="int").update(
            visible_for_users=True,
            title="Offline Integration",
            connection_string="frontier://FrontierInt/",
            use_in_gt_import=True,
        )
        dev = AccountType.objects.filter(name="dev").update(
            visible_for_users=True,
            title="Offline Preparation",
            connection_string="frontier://FrontierPrep/",
            use_in_gt_import=True,
        )
        pro = AccountType.objects.filter(name="pro").update(
            visible_for_users=True,
            title="Offline Production",
            connection_string="frontier://PromptProd/",
            use_in_gt_import=True,
        )

        arc = AccountType.objects.get(name="arc")
        integr = AccountType.objects.get(name="int")
        dev = AccountType.objects.get(name="dev")
        pro = AccountType.objects.get(name="pro")

        # global tag accounts
        global_tag_account, created = GTAccount.objects.get_or_create(pk=1, name="base global tag account")

        # global tag type category
        gttc_arch, created = GTTypeCategory.objects.get_or_create(pk=1, name="arch")
        gttc_int, created = GTTypeCategory.objects.get_or_create(pk=2, name="int")
        gttc_mc, created = GTTypeCategory.objects.get_or_create(pk=3, name="mc")
        gttc_offline, created = GTTypeCategory.objects.get_or_create(pk=4, name="offline")
        gttc_tier0, created = GTTypeCategory.objects.get_or_create(pk=5, name="tier0")
        gttc_online, created = GTTypeCategory.objects.get_or_create(pk=6, name="online")

        GTType.objects.get_or_create(
            pk=1, account_type=arc, gt_type_category=gttc_arch, type_conn_string="frontier://FrontierArc"
        )

        GTType.objects.get_or_create(
            pk=2, account_type=dev, gt_type_category=gttc_int, type_conn_string="frontier://FrontierPrep"
        )
        GTType.objects.get_or_create(
            pk=3, account_type=integr, gt_type_category=gttc_int, type_conn_string="frontier://FrontierInt"
        )

        GTType.objects.get_or_create(
            pk=4, account_type=dev, gt_type_category=gttc_mc, type_conn_string="frontier://FrontierPrep"
        )
        GTType.objects.get_or_create(
            pk=5, account_type=integr, gt_type_category=gttc_mc, type_conn_string="frontier://FrontierInt"
        )
        GTType.objects.get_or_create(
            pk=6, account_type=pro, gt_type_category=gttc_mc, type_conn_string="frontier://FrontierProd"
        )

        GTType.objects.get_or_create(
            pk=7, account_type=arc, gt_type_category=gttc_mc, type_conn_string="frontier://FrontierArc"
        )

        GTType.objects.get_or_create(
            pk=8, account_type=dev, gt_type_category=gttc_offline, type_conn_string="frontier://FrontierPrep"
        )
        GTType.objects.get_or_create(
            pk=9, account_type=integr, gt_type_category=gttc_offline, type_conn_string="frontier://FrontierInt"
        )
        GTType.objects.get_or_create(
            pk=10, account_type=pro, gt_type_category=gttc_offline, type_conn_string="frontier://FrontierProd"
        )

        GTType.objects.get_or_create(
            pk=11, account_type=dev, gt_type_category=gttc_tier0, type_conn_string="frontier://FrontierPrep"
        )
        GTType.objects.get_or_create(
            pk=12, account_type=integr, gt_type_category=gttc_tier0, type_conn_string="frontier://FrontierInt"
        )
        GTType.objects.get_or_create(
            pk=13, account_type=pro, gt_type_category=gttc_tier0, type_conn_string="frontier://PromptProd"
        )

        GTType.objects.get_or_create(
            pk=14,
            account_type=pro,
            gt_type_category=gttc_online,
            type_conn_string="frontier://(proxyurl=http://localhost:3128)(serverurl=http://localhost:8000/FrontierOnProd)(serverurl=http://localhost:8000/FrontierOnProd)(retrieve-ziplevel=0)(failovertoserver=no)",
        )

        # todo remove if possible
        GTType.objects.get_or_create(
            pk=15,
            account_type=pro,
            gt_type_category=gttc_online,
            type_conn_string="frontier://(proxyurl=http://localhost:3128)(serverurl=http://localhost:8000/FrontierOnProd)(serverurl=http://localhost:8000/FrontierOnProd)(serverurl=http://localhost:8000/FrontierOnProd)(retrieve-ziplevel=0)(failovertoserver=no)",
        )

        # todo for replacing
        GTType.objects.get_or_create(
            pk=16,
            account_type=pro,
            gt_type_category=gttc_online,
            type_conn_string="frontier://(proxyurl=http://localhost:3128)(serverurl=http://localhost:8000/FrontierOnProd)(serverurl=http://localhost:8000/FrontierOnProd)(retrieve-ziplevel=0)",
        )

        # There are records, where tag and record containers don't match (e.g. payload inspector shows parent container
        # ant recods provider shows child). these values are mapped by adding extra mapping
        #
        #        Not matching containers:
        # (tag container, record container). record containers has to be appended
        not_matching_containers = [
            # child                                    #parent
            (u"DTKeyedConfig", u"cond::BaseKeyed"),
            (u"PerformancePayloadFromBinnedTFormula", u"PerformancePayload"),
            (u"PerformancePayloadFromTFormula", u"PerformancePayload"),
            (u"PerformancePayloadFromTable", u"PerformancePayload"),
            (u"std::vector<unsigned long long>", u"cond::KeyList"),
        ]
        # for tag_container_name, record_container_name in not_matching_containers: #TODO: FIX: BS
        for tag_container_name, record_container_name in not_matching_containers:
            #            record_container, created = ObjectForRecords.objects.get_or_create(name=record_container_name)
            #            record_container.parent_name = tag_container_name
            #            record_container.save()
            tag_container, created = ObjectForRecords.objects.get_or_create(name=tag_container_name)
            tag_container.parent_name = record_container_name
            tag_container.save()

        try:
            flat_page = FlatPage.objects.get(url="/gtc/")
        except FlatPage.DoesNotExist:
            sites = Site.objects.all()
            flat_page = FlatPage(
                url="/gtc/",
                title="GTC start page",
                content="up and running",
                enable_comments=False,
                registration_required=True,
            )
            flat_page.save()
            for site in sites:
                flat_page.sites.add(site)
            flat_page.save()
Beispiel #54
0
    return re.sub('"/?images/', '"http://www.weevilmagazine.co.uk/images/', text.decode('utf-8'))

conn = MySQLdb.connect(host='127.0.0.1', user='******', passwd=getpass.getpass(), db='weevil') 
c = conn.cursor()

for id_, year in committees.items():
    c.execute('SELECT introtext FROM jos_content WHERE id={0}'.format(id_))
    for row in c:
        committee = Committee(year=year)
        committee.text = fixtext(row[0])
        committee.save()

for id_, url in flat.items():
    c.execute('SELECT introtext FROM jos_content WHERE id={0}'.format(id_))
    for row in c:
        flatpage = FlatPage(url=url)
        flatpage.content = fixtext(row[0])
        flatpage.save()
        flatpage.sites.add(1)

weevils = {}
c.execute('SELECT id,description FROM jos_categories WHERE section=9;')
for row in c:
    if row[0] in cat:
        i = cat[row[0]]
        weevil = Magazine(issue_number=i)
        weevil.text = fixtext(row[1])
        weevil.cover = covers[i].format(i)
        weevils[i] = weevil
        weevil.save()
Beispiel #55
0
 def test_get_absolute_url_urlencodes(self):
     pf = FlatPage(title="Café!", url='/café/')
     self.assertEqual(pf.get_absolute_url(), '/caf%C3%A9/')
Beispiel #56
0
def menu():
    flatpages = FlatPage.all().order('title')
    if flatpages:
      for i in range(len(flatpages)):
        menu = '<a href="'+flatpages[i].url+'" title="'+flatpages[i].title+'">'+flatpages[i].title+'</a>'
      return menu 
Beispiel #57
0
        Usage:

        >>> EditorTypesEnum.get_editor(editor_id=0)
        (<class 'redactor.widgets.RedactorEditor'>, {})

        :param editor_id: int
        :return: tuple
        """
        return first(
            (e for i, e in enumerate(cls.EDITOR_TYPES) if i == editor_id))


# add additional field document_set
FlatPage.add_to_class(
    'document_set', GenericRelation(FileStorage)
)

# add additional field type_editor
FlatPage.add_to_class(
    'type_editor', models.IntegerField(
        verbose_name=_("Editor_type"),
        default=0,
        choices=EditorTypesEnum.get_choices()
    )
)

# add additional field file_set
FlatPage.add_to_class(
    'file_set', GenericRelation(RelativeFileStorage)
)