Exemple #1
0
    def queryMyGithub(self):
        conn = httplib.HTTPSConnection(host = 'api.github.com')

        if self.etag is not None:
            if self.lastTimeFetchedGithub is not None and self.myGithubInfo is not None:
                delta = datetime.timedelta(minutes = 20)
                now = datetime.datetime.now()
                if now - self.lastTimeFetchedGithub < delta:
                    return self.myGithubInfo

            conn.request(method = 'GET', url = '/users/lpgray', headers = {'User-Agent' : 'lpgray', 'If-None-Match' : self.etag})
            resp = conn.getresponse()
            self.etag = resp.getheader('ETag')
            if resp.status is 304:
                conn.close()
                return self.myGithubInfo
            else:
                self.myGithubInfo = json.loads(resp.read())
                conn.close()
                return self.myGithubInfo
        else:
            conn.request(method = 'GET', url = '/users/lpgray', headers = {'User-Agent' : 'lpgray'})
            resp = conn.getresponse()
            if resp.status is 200:
                self.etag = resp.getheader('ETag')
                self.myGithubInfo = json.loads(resp.read())
                self.lastTimeFetchedGithub = datetime.datetime.now()
                conn.close()
                return self.myGithubInfo
            else:
                file = open(settings.PROJECT_PATH + '/github_profile.json')
                self.myGithubInfo = json.loads(file.read())
                file.close()
                conn.close()
                return self.myGithubInfo
    def render(self, name, value, attrs=None):
        output = super(TypeaheadTextInput, self).render(name=name, value=value, attrs=attrs,)
        if self.local != "":
            self.local = 'local: $.map('+self.local+', function(v) { return { value: v }; }),'

        if self.prefetch != "":
            self.prefetch = '''prefetch: {url: "'''+self.prefetch+'''",
                ttl: '''+str(self.prefetch_ttl*60000)+''',
                filter: function(list) {
                    return $.map(list, function(v) { return { value: v }; });
                }
            },'''

        if self.remote != "":
            self.remote = '''remote: {url: "'''+self.remote+'''",
                filter: function(list) {
                    return $.map(list, function(v) { return { value: v }; });
                }
            }'''

        stresponse = SimpleTemplateResponse("django_typeahead_textinput/typeahead-bloodhound-script.html",
                                            {"typeahead_name": "id_"+name,
                                             "typeahead_local": self.local,
                                             "typeahead_prefetch": self.prefetch,
                                             "typeahead_remote": self.remote})
        stresponse.render()
        output += stresponse.rendered_content
        return output
    def test_pickling(self):
        # Create a template response. The context is
        # known to be unpicklable (e.g., a function).
        response = SimpleTemplateResponse('first/test.html', {
            'value': 123,
            'fn': datetime.now,
        })
        self.assertRaises(ContentNotRenderedError,
                          pickle.dumps, response)

        # But if we render the response, we can pickle it.
        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEqual(unpickled_response.content, response.content)
        self.assertEqual(unpickled_response['content-type'], response['content-type'])
        self.assertEqual(unpickled_response.status_code, response.status_code)

        # ...and the unpickled response doesn't have the
        # template-related attributes, so it can't be re-rendered
        template_attrs = ('template_name', 'context_data', '_post_render_callbacks')
        for attr in template_attrs:
            self.assertFalse(hasattr(unpickled_response, attr))

        # ...and requesting any of those attributes raises an exception
        for attr in template_attrs:
            with self.assertRaises(AttributeError):
                getattr(unpickled_response, attr)
Exemple #4
0
def saveComment( request ):
    email = request.POST['email']
    usrname = request.POST['usrname']
    content = request.POST['content']
    article = Article.objects.get(id = request.POST['aId'])
    
    
    kwarg = {'user' : util.get_or_create_usr(email, usrname),'content' : content}
    
    desc = request.POST.get('memo', None)
    if desc : kwarg['desc'] = desc
    
    rootId = request.POST.get('rootId', None)
    if rootId : kwarg['root_komment'] = Comment.objects.get(id = rootId)
    
    kommentId = request.POST.get('cId', None)
    if content.strip().count('#-') is 1 and kommentId:
        pattern = re.compile('(#-).*(-#\s*)')
        content = pattern.sub('', content)
        komment = Comment.objects.get(id = kommentId)
        
        kwarg['content'] = content
        kwarg['komment'] = komment         
    else:
        kwarg['article'] = article
        
    comment = Comment(**kwarg)
    comment.save()
    
    resp = HttpResponseRedirect('/article/feeds?aId='+str(article.id)+'#comment-'+str(comment.id))
    ## if not request.COOKIES.has_key('email') or not request.COOKIES.has_key('usrname'):
    resp.set_cookie('email', value = email, max_age = 31536000, httponly = True)
    resp.set_cookie('usrname', value = usrname.encode('utf-8'), max_age = 31536000, httponly = True)
    
    return resp
Exemple #5
0
    def test_repickling(self):
        response = SimpleTemplateResponse("first/test.html", {"value": 123, "fn": datetime.now})
        self.assertRaises(ContentNotRenderedError, pickle.dumps, response)

        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)
        pickle.dumps(unpickled_response)
Exemple #6
0
def regenerate_widget():
    ads = Advert.objects.filter(sell=True, is_selled=False).order_by("-created")[:5]
    current_site = Site.objects.get_current()
    response = SimpleTemplateResponse("widget.html", {"ads": ads, "domain": current_site.domain})
    response.render()
    widget_file = open(os.path.join(settings.STATICFILES_DIRS[0], "widget.html"), "w")
    content = response.rendered_content.encode("utf-8")
    widget_file.write(content)
    widget_file.close()
 def process_template_response(self, string_template, user=None):
     request = HttpRequest()
     request.user = user
     context = Context({'request': request})
     template = BackendTemplate(Template(string_template).render(context))
     response = SimpleTemplateResponse(template, context)
     response.content = string_template
     mw = ToolbarMiddleware()
     return mw.process_response(request, response).render()
class NavBarTemplateTagTestCase(TestCase):

    def setUp(self):
        create_pages()

    def test_navbar_renders(self):
        t = Template('{% load pages_tags %}{% navbar %}')
        self.response = SimpleTemplateResponse(t)
        self.response.render()
        self.assertTrue(self.response.is_rendered)
Exemple #9
0
    def test_pickling_cookie(self):
        response = SimpleTemplateResponse("first/test.html", {"value": 123, "fn": datetime.now})

        response.cookies["key"] = "value"

        response.render()
        pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEqual(unpickled_response.cookies["key"].value, "value")
 def process_template_response(self, string_template):
     settings.TOOLBAR_INSTANT_UPDATE = False
     request = HttpRequest()
     context = Context({'request': request})
     node = Template(string_template).render(context)
     template = BackendTemplate(node)
     response = SimpleTemplateResponse(template, context)
     response.content = node
     mw = TextMiddleware()
     return mw.process_response(request, response).render()
 def process_template_response(self, name, default=''):
     settings.TOOLBAR_INSTANT_UPDATE = False
     request = HttpRequest()
     context = Context({'request': request})
     node = Template(
         '{%% load text %%}{%% text "%s" "%s" %%}' % (name, default)).render(context)
     template = BackendTemplate(node)
     response = SimpleTemplateResponse(template, context)
     response.content = node
     mw = TextMiddleware()
     return mw.process_template_response(request, response).render()
Exemple #12
0
 def process_response(self, request, response):
     if 300 <= int(response.status_code) < 400:
         redirect_to = response.get('Location', None)
         if redirect_to:
             status_line = '%s %s' % (response.status_code, response.reason_phrase)
             cookies = response.cookies
             context = {'redirect_to': redirect_to, 'status_line': status_line}
             # Using SimpleTemplateResponse avoids running global context processors.
             response = SimpleTemplateResponse('debug_toolbar/redirect.html', context, using='django')
             response.cookies = cookies
             response.render()
     return response
    def test_repickling(self):
        response = SimpleTemplateResponse('first/test.html', {
            'value': 123,
            'fn': datetime.now,
        })
        self.assertRaises(ContentNotRenderedError,
                          pickle.dumps, response)

        response.render()
        pickled_response = pickle.dumps(response)
        unpickled_response = pickle.loads(pickled_response)
        pickle.dumps(unpickled_response)
Exemple #14
0
def regenerate_widget():
    ads = Advert.objects.filter(sell=True, is_selled=False).\
        order_by('-created')[:5]
    current_site = Site.objects.get_current()
    response = SimpleTemplateResponse('widget.html', 
                                      {'ads' : ads, 
                                       'domain' : current_site.domain})
    response.render()
    widget_file = open(os.path.join(settings.STATICFILES_DIRS[0],
                                    'widget.html'), 'w')
    content = response.rendered_content.encode('utf-8')
    widget_file.write(content)
    widget_file.close()
    def test_pickling_cookie(self):
        response = SimpleTemplateResponse('first/test.html', {
            'value': 123,
            'fn': datetime.now,
        })

        response.cookies['key'] = 'value'

        response.render()
        pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL)
        unpickled_response = pickle.loads(pickled_response)

        self.assertEqual(unpickled_response.cookies['key'].value, 'value')
 def process_response(self, request, response):
     if 300 <= int(response.status_code) < 400:
         redirect_to = response.get("Location", None)
         if redirect_to:
             status_line = "%s %s" % (response.status_code, response.reason_phrase)
             cookies = response.cookies
             context = {"redirect_to": redirect_to, "status_line": status_line}
             # Using SimpleTemplateResponse avoids running global context processors.
             response = SimpleTemplateResponse(
                 "debug_toolbar/redirect.html", context
             )
             response.cookies = cookies
             response.render()
     return response
Exemple #17
0
class GetPageTemplateTagTestCase(TestCase):

    urls = 'ostinato.pages.urls'

    def setUp(self):
        create_pages()
        t = Template('{% load pages_tags %}{% get_page "page-1" as somepage %}{{ somepage }}')
        self.response = SimpleTemplateResponse(t)

    def test_tag_renders(self):
        self.response.render()
        self.assertTrue(self.response.is_rendered)

    def test_page_in_content(self):
        self.response.render()
        self.assertIn('Page 1', self.response.content)
Exemple #18
0
    def test_post_callbacks(self):
        "Rendering a template response triggers the post-render callbacks"
        post = []

        def post1(obj):
            post.append('post1')
        def post2(obj):
            post.append('post2')

        response = SimpleTemplateResponse('first/test.html', {})
        response.add_post_render_callback(post1)
        response.add_post_render_callback(post2)

        # When the content is rendered, all the callbacks are invoked, too.
        response.render()
        self.assertEqual('First template\n', response.content)
        self.assertEqual(post, ['post1','post2'])
Exemple #19
0
class BreadCrumbsTempalteTagTestCase(TestCase):

    urls = 'ostinato.pages.urls'

    def setUp(self):
        create_pages()
        t = Template('{% load pages_tags %}{% get_page "page-3" as page %}{% breadcrumbs %}')
        self.response = SimpleTemplateResponse(t)

    def test_tag_renders(self):
        self.response.render()
        self.assertTrue(self.response.is_rendered)

    def test_breadcrumbs_in_context(self):
        self.response.render()
        self.assertIn('<a href="/">Page 1</a> &gt;&gt; ', self.response.content)
        self.assertIn('<strong>Page 3</strong>', self.response.content)
Exemple #20
0
    def test_post_callbacks(self):
        "Rendering a template response triggers the post-render callbacks"
        post = []

        def post1(obj):
            post.append("post1")

        def post2(obj):
            post.append("post2")

        response = SimpleTemplateResponse("first/test.html", {})
        response.add_post_render_callback(post1)
        response.add_post_render_callback(post2)

        # When the content is rendered, all the callbacks are invoked, too.
        response.render()
        self.assertEqual(response.content, b"First template\n")
        self.assertEqual(post, ["post1", "post2"])
    def test_template_resolving(self):
        response = SimpleTemplateResponse('first/test.html')
        response.render()
        self.assertEqual(response.content, b'First template\n')

        templates = ['foo.html', 'second/test.html', 'first/test.html']
        response = SimpleTemplateResponse(templates)
        response.render()
        self.assertEqual(response.content, b'Second template\n')

        response = self._response()
        response.render()
        self.assertEqual(response.content, b'foo')
Exemple #22
0
    def test_template_resolving(self):
        response = SimpleTemplateResponse("first/test.html")
        response.render()
        self.assertEqual("First template\n", response.content)

        templates = ["foo.html", "second/test.html", "first/test.html"]
        response = SimpleTemplateResponse(templates)
        response.render()
        self.assertEqual("Second template\n", response.content)

        response = self._response()
        response.render()
        self.assertEqual(response.content, "foo")
Exemple #23
0
class NavBarTemplateTagTestCase(TestCase):

    urls = 'ostinato.pages.urls'

    def setUp(self):
        create_pages()

        t = Template('{% load pages_tags %}{% navbar %}')
        self.response = SimpleTemplateResponse(t)

    def test_navbar_renders(self):
        self.response.render()
        self.assertTrue(self.response.is_rendered)

    def test_navbar_content(self):
        self.response.render()

        self.assertIn('<a href="/">Page 1</a>',
            self.response.content)
        self.assertIn('<a href="/page-2/">P2</a>', 
            self.response.content)
Exemple #24
0
    def make_result_list(self):
        # Get search parameters from the query string.
        self.base_queryset = self.queryset()
        self.list_queryset = self.get_list_queryset()
        self.ordering_field_columns = self.get_ordering_field_columns()
        self.paginator = self.get_paginator()

        # Get the number of objects, with admin filters applied.
        self.result_count = self.paginator.count

        # Get the total number of objects, with no admin filters applied.
        # Perform a slight optimization: Check to see whether any filters were
        # given. If not, use paginator.hits to calculate the number of objects,
        # because we've already done paginator.hits and the value is cached.
        if not self.list_queryset.query.where:
            self.full_result_count = self.result_count
        else:
            self.full_result_count = self.base_queryset.count()

        self.can_show_all = self.result_count <= self.list_max_show_all
        self.multi_page = self.result_count > self.list_per_page

        # Get the list of objects to display on this page.
        if (self.show_all and self.can_show_all) or not self.multi_page:
            self.result_list = self.list_queryset._clone()
        else:
            try:
                self.result_list = self.paginator.page(
                    self.page_num + 1).object_list
            except InvalidPage:
                if ERROR_FLAG in self.request.GET.keys():
                    return SimpleTemplateResponse('xadmin/views/invalid_setup.html', {
                        'title': _('Database error'),
                    })
                return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1')
        self.has_more = self.result_count > (
            self.list_per_page * self.page_num + len(self.result_list))
Exemple #25
0
    def test_post_callbacks(self):
        "Rendering a template response triggers the post-render callbacks"
        post = []

        def post1(obj):
            post.append("post1")

        def post2(obj):
            post.append("post2")

        response = SimpleTemplateResponse("first/test.html", {})
        response.add_post_render_callback(post1)
        response.add_post_render_callback(post2)

        # When the content is rendered, all the callbacks are invoked, too.
        response.render()
        self.assertEqual(response.content, b"First template\n")
        self.assertEqual(post, ["post1", "post2"])
Exemple #26
0
def listview_sales(request):

    result = ""
    users = []

    for u in User.objects.extra(
            select=
        {
            'campaign_name':
            'SELECT name FROM users_usercampaigndata WHERE users_usercampaigndata.user_id = auth_user.id',
            'country':
            'SELECT country FROM users_usercampaigndata WHERE users_usercampaigndata.user_id = auth_user.id',
            'referrer':
            'SELECT referrer FROM users_usercampaigndata WHERE users_usercampaigndata.user_id = auth_user.id',
            'num_videos':
            'SELECT COUNT(*) FROM videos_video JOIN users_team  ON (videos_video.team_id = users_team.id) WHERE users_team.owner_id = auth_user.id AND videos_video.archived != True',
            'num_videos_published':
            'SELECT COUNT(*) FROM videos_video JOIN users_team  ON (videos_video.team_id = users_team.id) WHERE users_team.owner_id = auth_user.id AND videos_video.archived != True AND videos_video.published = 1',
        }).order_by('-date_joined'):
        user = [
            "<span>" + helpers.userlink(u) + "</span>",
            u.email,
            "" + str(u.country if u.country else '') + "",
            "" + str(u.campaign_name if u.campaign_name else '') + "",
            referral_link(u.referrer),
            "<b>" + str(u.num_videos) + "</b> v",
            "<b>" + str(u.num_videos_published) + "</b> p",
            "<b>" + str(u.date_joined.date()) + "</b>",
        ]
        users.append(user)

    result += helpers.table(users)

    return SimpleTemplateResponse("insights/base.html", {
        "title": "All Users (Sales List)",
        "insight_content": result
    })
Exemple #27
0
    def test_post_callbacks(self):
        "Rendering a template response triggers the post-render callbacks"
        post = []

        def post1(obj):
            post.append('post1')

        def post2(obj):
            post.append('post2')

        response = SimpleTemplateResponse('first/test.html', {})
        response.add_post_render_callback(post1)
        response.add_post_render_callback(post2)

        # When the content is rendered, all the callbacks are invoked, too.
        response.render()
        self.assertEqual(response.content, b'First template\n')
        self.assertEqual(post, ['post1', 'post2'])
Exemple #28
0
    def add_view(self, request):
        """    添加页面    """

        if request.method == 'GET':
            form = self.get_model_form_cls()

        elif request.method == "POST":
            form = self.get_model_form_cls(data=request.POST,
                                           files=request.FILES)
            if form.is_valid():
                obj = form.save()
                popup_id = request.GET.get("_popup")
                if popup_id:
                    context = {
                        'pk': obj.pk,
                        'value': str(obj),
                        'popup_id': popup_id
                    }
                    return SimpleTemplateResponse(
                        'carry/popup_response.html',
                        {"popup_response_data": json.dumps(context)})
                else:
                    _change_filter = request.GET.get('_change_filter')
                    if _change_filter:
                        change_list_url = "{0}?{1}".format(
                            self.changelist_url(), _change_filter)
                    else:
                        change_list_url = self.changelist_url()
                    return redirect(change_list_url)
        else:
            raise Exception('当前URL只支持GET/POST方法')
        context = {'form': form}
        return TemplateResponse(
            request, self.add_form_template or [
                'carry/%s/%s/add.html' % (self.app_label, self.model_name),
                'carry/%s/add.html' % self.app_label, 'carry/add.html'
            ], context)
Exemple #29
0
def sql_select(request):
    """Returns the output of the SQL SELECT statement"""
    form = SQLSelectForm(request.POST or None)

    if form.is_valid():
        sql = form.cleaned_data['raw_sql']
        params = form.cleaned_data['params']
        cursor = form.cursor
        cursor.execute(sql, params)
        headers = [d[0] for d in cursor.description]
        result = cursor.fetchall()
        cursor.close()
        context = {
            'result': result,
            'sql': form.reformat_sql(),
            'duration': form.cleaned_data['duration'],
            'headers': headers,
            'alias': form.cleaned_data['alias'],
        }
        # Using SimpleTemplateResponse avoids running global context processors.
        return SimpleTemplateResponse('debug_toolbar/panels/sql_select.html',
                                      context,
                                      using='django')
    return HttpResponseBadRequest('Form errors')
Exemple #30
0
 def test_random_zone_ad_renders(self):
     template = Template(
         "{% load adzone_tags %}{% random_zone_ad 'sidebar' %}")
     response = SimpleTemplateResponse(template)
     response.render()
     self.assertTrue(response.is_rendered)
Exemple #31
0
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    template_origin_name = request.GET.get('template_origin', None)
    if template_origin_name is None:
        return HttpResponseBadRequest('"template_origin" key is required')
    try:
        template_origin_name = signing.loads(template_origin_name)
    except Exception:
        return HttpResponseBadRequest('"template_origin" is invalid')
    template_name = request.GET.get('template', template_origin_name)

    final_loaders = []
    loaders = Engine.get_default().template_loaders

    for loader in loaders:
        if loader is not None:
            # When the loader has loaders associated with it,
            # append those loaders to the list. This occurs with
            # django.template.loaders.cached.Loader
            if hasattr(loader, 'loaders'):
                final_loaders += loader.loaders
            else:
                final_loaders.append(loader)

    for loader in final_loaders:
        if Origin:  # django>=1.9
            origin = Origin(template_origin_name)
            try:
                source = loader.get_contents(origin)
                break
            except TemplateDoesNotExist:
                pass
        else:  # django<1.9
            try:
                source, _ = loader.load_template_source(template_name)
                break
            except TemplateDoesNotExist:
                pass
    else:
        source = "Template Does Not Exist: %s" % (template_origin_name, )

    try:
        from pygments import highlight
        from pygments.lexers import HtmlDjangoLexer
        from pygments.formatters import HtmlFormatter

        source = highlight(source, HtmlDjangoLexer(), HtmlFormatter())
        source = mark_safe(source)
        source.pygmentized = True
    except ImportError:
        pass

    # Using SimpleTemplateResponse avoids running global context processors.
    return SimpleTemplateResponse('debug_toolbar/panels/template_source.html',
                                  {
                                      'source': source,
                                      'template_name': template_name
                                  })
Exemple #32
0
 def _response(self, template='foo', *args, **kwargs):
     return SimpleTemplateResponse(Template(template), *args, **kwargs)
Exemple #33
0
 def setUp(self):
     create_pages()
     t = Template('{% load pages_tags %}{% get_page "page-1" as somepage %}{{ somepage }}')
     self.response = SimpleTemplateResponse(t)
Exemple #34
0
 def test_tag_renders(self):
     t = Template('{% load pages_tags %}{% get_page slug="page-1" as somepage %}{{ somepage.title }}')
     response = SimpleTemplateResponse(t)
     response.render()
     self.assertTrue(response.is_rendered)
Exemple #35
0
 def test_tag_renders(self):
     create_pages()
     t = Template('{% load pages_tags %}{% get_page slug="page-3" as page %}{% breadcrumbs %}')
     response = SimpleTemplateResponse(t)
     response.render()
     self.assertTrue(response.is_rendered)
Exemple #36
0
def addGallery(request):
    if request.method == 'GET':
        form = UploadForm()
        c = RequestContext({'form': form})
        c.update(csrf(request))
        return (SimpleTemplateResponse('admin/upload.html', c))
    else:
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            # First, copy zipfile to a tmpfile
            zipfile = NamedTemporaryFile(delete=False)
            zipfile.write(request.FILES['file'].read())
            zipfile.close()
            # Now we got the Zip, unzip it!!
            imagesObj = imagesFromZip(zipfile.name)
            imagesList = imagesObj.listImages()
            # Is there images in this zip ?
            if len(imagesList) > 0:
                # regexp for extractiong name ...
                nameRe = re.compile('/([^/]+)$')
                # Create corresponding gallery
                gallery = Gallery()
                gallery.title = form.cleaned_data['title']
                gallery.desc = form.cleaned_data['desc']
                gallery.category = form.cleaned_data['category']
                gallery.save()  # Must save gallery
                # Now, for each images in it, create an image object and bind it to gallery
                for imgPath in imagesList:
                    src = PILImage.open(imgPath)
                    m = nameRe.search(imgPath)
                    imgObj = Image()
                    imgObj.gallery = gallery
                    # First, put the original sized picture
                    # use StringIO hack to save image to a string ...
                    output = StringIO.StringIO()
                    src.save(output, 'JPEG')
                    imgObj.original.save(m.groups()[0],
                                         ContentFile(output.getvalue()))
                    output.close()
                    # Then, resize it to something like 1600*1200
                    (orig_w, orig_h) = src.size
                    orig_s = orig_w * orig_h
                    new_s = 1024 * 768
                    ratio = orig_s / new_s
                    # Resize only if requested size is lower than original
                    if ratio > 1:
                        (new_w, new_h) = (orig_w / (sqrt(ratio)),
                                          orig_h / (sqrt(ratio)))
                        resized = src.resize((int(new_w), int(new_h)))
                    else:  # Else, just keep original one ...
                        (new_w, new_h) = (orig_w, orig_h)
                        resized = src
                    output = StringIO.StringIO()
                    resized.save(output, 'JPEG')
                    imgObj.screen.save(m.groups()[0],
                                       ContentFile(output.getvalue()))
                    output.close()
                    # Finally, get a thumb of 150px*150px, work on resized picture to be faster
                    if new_w < new_h:
                        maxi = new_w
                    else:
                        maxi = new_h
                    thumb = resized.transform((150, 150), PILImage.EXTENT,
                                              (0, 0, maxi, maxi))
                    output = StringIO.StringIO()
                    thumb.save(output, 'JPEG')
                    imgObj.thumb.save(m.groups()[0],
                                      ContentFile(output.getvalue()))
                    output.close()
                    imgObj.save()
                gallery.save()
                return (HttpResponseRedirect(
                    reverse('gallery.admin.views.editGallery',
                            kwargs={'id': gallery.pk})))
            # Cleanup...
            imagesObj.cleanup()
            os.rm(zipfile)
        else:
            c = RequestContext(request, csrf(request))
            c['form'] = form
            return (SimpleResponseTemplate('admin/upload.html', c))
Exemple #37
0
    def test_localisationmiddleware_process_response(self):
        import geoip2

        class Context(dict):
            pass

        context = Context()
        context['page_obj'] = Context()
        context['page_obj'].has_other_pages = lambda: False

        response = SimpleTemplateResponse('pagination/pagination.html', context)
        localisation_middleware = LocalisationMiddleware()

        geoip_dat_file = '{}/geolite2/GeoLite2-Country.mmdb'.format(os.path.dirname(os.path.realpath(__file__)))

        self.request = self.factory.get('/media/')
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)
        self.assertEqual(processed_response, response)
        self.assertEqual(processed_response.status_code, 200)

        obj = Country.objects.create(
            code='GB',
        )

        self.request = self.factory.get('/')
        localisation_middleware.process_request(self.request)

        try:
            processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)
        except geoip2.errors.AddressNotFoundError:
            self.request.country = obj
            processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response, response)

        # Give ourselves a direct IP.
        self.request = self.factory.get('/')
        self.request.META['REMOTE_ADDR'] = '212.58.246.103'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response.status_code, 302)
        self.assertNotEqual(processed_response, response)
        self.assertEqual(self.request.country, obj)

        # Give ourselves a proxied IP.
        self.request = self.factory.get('/')
        self.request.META['HTTP_X_FORWARDED_FOR'] = '212.58.246.103'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response.status_code, 302)
        self.assertNotEqual(processed_response, response)
        self.assertEqual(self.request.country, obj)

        # Give ourselves a French IP.
        self.request = self.factory.get('/')
        self.request.META['REMOTE_ADDR'] = '2.15.255.255'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response.status_code, 200)
        self.assertEqual(processed_response, response)
        self.assertIsNone(self.request.country)

        obj = Country.objects.create(
            code='US',
        )

        self.request = self.factory.get('/')
        # Give ourselves a US West IP.
        self.request.META['REMOTE_ADDR'] = '52.52.95.213'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response.status_code, 302)
        self.assertNotEqual(processed_response, response)
        self.assertEqual(self.request.country, obj)

        obj = Country.objects.create(
            code='IN',
        )

        self.request = self.factory.get('/')

        # Give ourselves an Indian IP.
        self.request.META['REMOTE_ADDR'] = '13.232.220.164'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        self.assertEqual(processed_response.status_code, 302)
        self.assertNotEqual(processed_response, response)
        self.assertEqual(self.request.country, obj)

        # Give ourselves a Japanese IP
        self.request.META['REMOTE_ADDR'] = '52.194.115.181'
        localisation_middleware.process_request(self.request)
        processed_response = localisation_middleware.process_response(self.request, response, geoip_path=geoip_dat_file)

        # Test Indian country code with Japanese IP
        self.assertNotEqual(self.request.country, obj)
Exemple #38
0
    def response_add(self, request, obj, post_url_continue=None):
        """
    Determines the HttpResponse for the add_view stage.
    """
        opts = obj._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': force_text(obj)
        }
        # Here, we distinguish between different save types by checking for
        # the presence of keys in request.POST.
        if '_popup' in request.POST:
            to_field = request.POST.get('_to_field')
            if to_field:
                attr = str(to_field)
            else:
                attr = obj._meta.pk.attname
            value = obj.serializable_value(attr)
            return SimpleTemplateResponse(
                'admin/popup_response.html',
                {
                    'pk_value':
                    escape(pk_value),  # for possible backwards-compatibility
                    'value': escape(value),
                    'obj': escapejs(obj)
                })

        elif "_continue" in request.POST:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was added successfully. You may edit it again below.'
            ) % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            if post_url_continue is None:
                post_url_continue = request.prefix + reverse(
                    'admin:%s_%s_change' % (opts.app_label, opts.model_name),
                    args=(quote(pk_value), ),
                    current_app=self.admin_site.name)
            post_url_continue = add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, post_url_continue)
            return HttpResponseRedirect(post_url_continue)

        elif "_addanother" in request.POST:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.'
            ) % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.prefix + request.path
            redirect_url = add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was added successfully.') % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            # Redirect to previous url
            return HttpResponseRedirect(
                "%s%s" % (request.prefix,
                          request.session['crumbs'][request.prefix][-2][2]))
Exemple #39
0
    def response_change(self, request, obj):
        """
    Determines the HttpResponse for the change_view stage.
    """
        if '_popup' in request.POST:
            to_field = request.POST.get('_to_field')
            attr = str(to_field) if to_field else obj._meta.pk.attname
            # Retrieve the `object_id` from the resolved pattern arguments.
            value = request.resolver_match.args[0]
            new_value = obj.serializable_value(attr)
            return SimpleTemplateResponse(
                'admin/popup_response.html', {
                    'action': 'change',
                    'value': escape(value),
                    'obj': escapejs(obj),
                    'new_value': escape(new_value),
                })

        opts = self.model._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': force_text(obj)
        }
        if "_continue" in request.POST:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was changed successfully. You may edit it again below.'
            ) % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.prefix + request.path
            redirect_url = add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_saveasnew" in request.POST:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was added successfully. You may edit it again below.'
            ) % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.prefix + reverse(
                'admin:%s_%s_change' % (opts.app_label, opts.model_name),
                args=(pk_value, ),
                current_app=self.admin_site.name)
            redirect_url = add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_addanother" in request.POST:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.'
            ) % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.prefix + reverse(
                'admin:%s_%s_add' % (opts.app_label, opts.model_name),
                current_app=self.admin_site.name)
            redirect_url = add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            # Translators: Translation included with Django
            msg = _(
                'The %(name)s "%(obj)s" was changed successfully.') % msg_dict
            self.message_user(request, msg, messages.SUCCESS)
            # Redirect to previous url
            return HttpResponseRedirect(
                "%s%s" % (request.prefix,
                          request.session['crumbs'][request.prefix][-2][2]))
Exemple #40
0
def overview_view(request):
    return SimpleTemplateResponse("products/overview.html")
Exemple #41
0
    def changelist_view(self, request, extra_context=None):
        """
        Overriding the changelist view of ModelAdmin to allow the list view to be displayed
        when the user only has view permissions.
        In this case, the list view will be displayed without the 'Add' button and without list actions
        """
        from django.contrib.admin.views.main import ERROR_FLAG
        opts = self.model._meta
        app_label = opts.app_label

        # Adding check for view permissions
        if not self.has_change_permission(
                request, None) and not self.has_view_permission(request, None):
            raise PermissionDenied

        list_display = self.get_list_display(request)
        list_display_links = self.get_list_display_links(request, list_display)
        list_filter = self.get_list_filter(request)
        search_fields = self.get_search_fields(request)

        # If use only has view permissions, then don't render actions
        # Check actions to see if any are available on this changelist
        if self.has_change_permission(request, None):
            actions = self.get_actions(request)
            if actions:
                # Add the action checkboxes if there are any actions available.
                list_display = ['action_checkbox'] + list(list_display)
        else:
            actions = None

        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(request, self.model, list_display,
                            list_display_links, list_filter,
                            self.date_hierarchy, search_fields,
                            self.list_select_related, self.list_per_page,
                            self.list_max_show_all, self.list_editable, self)

        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given
            # and the 'invalid=1' parameter was already in the query string,
            # something is screwed up with the database, so display an error
            # page.
            if ERROR_FLAG in request.GET.keys():
                return SimpleTemplateResponse('admin/invalid_setup.html', {
                    'title': _('Database error'),
                })
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        # If the request was POSTed, this might be a bulk action or a bulk
        # edit. Try to look up an action or confirmation first, but if this
        # isn't an action the POST will fall through to the bulk edit check,
        # below.
        action_failed = False
        selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

        # Actions with no confirmation
        if (actions and request.method == 'POST' and 'index' in request.POST
                and '_save' not in request.POST):
            if selected:
                response = self.response_action(
                    request, queryset=cl.get_queryset(request))
                if response:
                    return response
                else:
                    action_failed = True
            else:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                self.message_user(request, msg, messages.WARNING)
                action_failed = True

        # Actions with confirmation
        if (actions and request.method == 'POST'
                and helpers.ACTION_CHECKBOX_NAME in request.POST
                and 'index' not in request.POST
                and '_save' not in request.POST):
            if selected:
                response = self.response_action(
                    request, queryset=cl.get_queryset(request))
                if response:
                    return response
                else:
                    action_failed = True

        # If we're allowing changelist editing, we need to construct a formset
        # for the changelist given all the fields to be edited. Then we'll
        # use the formset to validate/process POSTed data.
        formset = cl.formset = None

        # Handle POSTed bulk-edit data.
        if (request.method == "POST" and cl.list_editable
                and '_save' in request.POST and not action_failed):
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(request.POST,
                                           request.FILES,
                                           queryset=cl.result_list)
            if formset.is_valid():
                changecount = 0
                for form in formset.forms:
                    if form.has_changed():
                        obj = self.save_form(request, form, change=True)
                        self.save_model(request, obj, form, change=True)
                        self.save_related(request,
                                          form,
                                          formsets=[],
                                          change=True)
                        change_msg = self.construct_change_message(
                            request, form, None)
                        self.log_change(request, obj, change_msg)
                        changecount += 1

                if changecount:
                    if changecount == 1:
                        name = force_text(opts.verbose_name)
                    else:
                        name = force_text(opts.verbose_name_plural)
                    msg = ungettext(
                        "%(count)s %(name)s was changed successfully.",
                        "%(count)s %(name)s were changed successfully.",
                        changecount) % {
                            'count': changecount,
                            'name': name,
                            'obj': force_text(obj)
                        }
                    self.message_user(request, msg, messages.SUCCESS)

                return HttpResponseRedirect(request.get_full_path())

        # Handle GET -- construct a formset for display.
        elif cl.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(queryset=cl.result_list)

        # Build the list of media to be used by the formset.
        if formset:
            media = self.media + formset.media
        else:
            media = self.media

        # Build the action form and populate it with available actions.
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(
                request)
        else:
            action_form = None

        selection_note_all = ungettext('%(total_count)s selected',
                                       'All %(total_count)s selected',
                                       cl.result_count)

        context = dict(
            self.admin_site.each_context(request),
            module_name=force_text(opts.verbose_name_plural),
            selection_note=_('0 of %(cnt)s selected') %
            {'cnt': len(cl.result_list)},
            selection_note_all=selection_note_all %
            {'total_count': cl.result_count},
            title=cl.title,
            is_popup=cl.is_popup,
            to_field=cl.to_field,
            cl=cl,
            media=media,
            has_add_permission=self.has_add_permission(request),
            opts=cl.opts,
            action_form=action_form,
            actions_on_top=self.actions_on_top,
            actions_on_bottom=self.actions_on_bottom,
            actions_selection_counter=self.actions_selection_counter,
            preserved_filters=self.get_preserved_filters(request),
        )
        context.update(extra_context or {})

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request, self.change_list_template or [
                'admin/%s/%s/change_list.html' % (app_label, opts.model_name),
                'admin/%s/change_list.html' % app_label,
                'admin/change_list.html'
            ], context)
Exemple #42
0
 def test_random_category_ad_renders(self):
     template = Template("{% load adzone_tags %}{% random_category_ad 'sidebar' 'internet-services' %}")
     response = SimpleTemplateResponse(template)
     response.render()
     self.assertTrue(response.is_rendered)
Exemple #43
0
def export(coll, context):
    '''
        Export des données d'une collection
    '''

    # Cherchons la configuration pour avoir des valeurs par défaut
    config = Config.objects.get(code=CODE_CONFIG_DEFAUT)
    periode = range(config.annee_min_publis, config.annee_max_publis + 1)

    # Lecture des modèles de graphiques
    diag_barres = SimpleTemplateResponse('publis/charts/diagramme_barres.json',
                                         {})
    diag_camembert = SimpleTemplateResponse(
        'publis/charts/diagramme_camembert.json', {})

    # On  crée le répertoire pour la collection s'il n'existe pas
    coll_dir = os.path.join(settings.EXPORT_DIR, coll.code)
    if not os.path.isdir(coll_dir):
        os.mkdir(coll_dir)
    prefixe_fichier = "graphiques_" + coll.code

    # Export des graphiques
    diag_barres.context_data["chart_annees"] = list(periode)
    diag_barres.context_data[
        "chart_donnees"] = Publication.stats_par_annee_type(
            coll.code, config.annee_min_publis, config.annee_max_publis)
    with open(os.path.join(coll_dir, prefixe_fichier + "_par_annee_type.json"),
              mode='w',
              encoding="utf-8") as filehandle:
        filehandle.write(str(diag_barres.rendered_content))
    diag_barres.context_data[
        "chart_donnees"] = Publication.stats_par_annee_classement(
            coll.code, config.annee_min_publis, config.annee_max_publis)
    with open(os.path.join(coll_dir,
                           prefixe_fichier + "_par_annee_classement.json"),
              mode='w',
              encoding="utf-8") as filehandle:
        filehandle.write(str(diag_barres.rendered_content))

    diag_camembert.context_data["chart_annees"] = periode
    diag_camembert.context_data[
        "chart_donnees"] = Publication.stats_par_classement(
            coll.code, config.annee_min_publis, config.annee_max_publis)
    with open(os.path.join(coll_dir, prefixe_fichier + "_par_classement.json"),
              mode='w',
              encoding="utf-8") as filehandle:
        filehandle.write(str(diag_camembert.rendered_content))

    # Export des publis en Bibtex
    prefixe_fichier = "publis_" + coll.code
    for classement in ClassementPubli.objects.all():
        with open(os.path.join(
                coll_dir,
                prefixe_fichier + "_{0}.bib".format(classement.code)),
                  mode='w',
                  encoding="utf-8") as filehandle:
            for publi in Publication.objects.filter(
                    annee__gte=config.annee_min_publis).filter(
                        annee__lte=config.annee_max_publis).filter(
                            classement=classement).filter(collections=coll):
                filehandle.writelines([publi.bibtex_hal(), "\n"])

    # Pour finir on met tout ça dans un zip et on envoie
    contenu_zip = BytesIO()
    zf = zipfile.ZipFile(contenu_zip, "w")
    for file in os.listdir(coll_dir):
        if file.endswith(".json") or file.endswith(".bib") or file.endswith(
                ".tex"):
            zf.write(os.path.join(coll_dir, file), file)
    zf.close()

    return contenu_zip
Exemple #44
0
def account(request):
    return SimpleTemplateResponse(get_template('account.html'))
Exemple #45
0
 def _response(self, template='foo', *args, **kwargs):
     template = engines['django'].from_string(template)
     return SimpleTemplateResponse(template, *args, **kwargs)
Exemple #46
0
    def changelist_view(self, request, extra_context=None):
        if not self.has_change_permission(request, None):
            raise PermissionDenied

        if not SEARCH_VAR in request.GET or "action" in request.POST:
            # Do the usual song and dance.
            return super(MetaShareSearchModelAdmin,
                         self).changelist_view(request, extra_context)
        # Do a search of just this model and populate a Changelist with the
        # returned bits.
        if not self.model in connections['default'].get_unified_index(
        ).get_indexed_models():
            # Oops. That model isn't being indexed. Return the usual
            # behavior instead.
            return super(MetaShareSearchModelAdmin,
                         self).changelist_view(request, extra_context)

        # So. Much. Boilerplate.
        # Why copy-paste a few lines when you can copy-paste TONS of lines?
        list_display = self.get_list_display(request)
        list_display_links = self.get_list_display_links(request, list_display)
        list_filter = self.get_list_filter(request)
        search_fields = self.get_search_fields(request)

        ChangeListClass = self.get_changelist(request)
        try:
            changelist = ChangeListClass(
                request, self.model, list_display, list_display_links,
                list_filter, self.date_hierarchy, search_fields,
                self.list_select_related, self.list_per_page,
                self.list_max_show_all, self.list_editable, self)

        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given
            # and the 'invalid=1' parameter was already in the query string,
            # something is screwed up with the database, so display an error
            # page.
            if ERROR_FLAG in request.GET.keys():
                return SimpleTemplateResponse('admin/invalid_setup.html', {
                    'title': _('Database error'),
                })
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
        formset = changelist.formset = None
        media = self.media

        # Build the action form and populate it with available actions.
        # Check actions to see if any are available on this changelist
        actions = self.get_actions(request)
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(
                request)
        else:
            action_form = None

        selection_note = ungettext('0 of %(count)d selected',
                                   'of %(count)d selected',
                                   len(changelist.result_list))
        selection_note_all = ungettext('%(total_count)s selected',
                                       'All %(total_count)s selected',
                                       changelist.result_count)

        context = {
            'module_name':
            force_unicode(self.model._meta.verbose_name_plural),
            'selection_note':
            selection_note % {
                'count': len(changelist.result_list)
            },
            'selection_note_all':
            selection_note_all % {
                'total_count': changelist.result_count
            },
            'title':
            changelist.title,
            'is_popup':
            changelist.is_popup,
            'cl':
            changelist,
            'media':
            media,
            'has_add_permission':
            self.has_add_permission(request),
            'app_label':
            self.model._meta.app_label,
            'action_form':
            action_form,
            'actions_on_top':
            self.actions_on_top,
            'actions_on_bottom':
            self.actions_on_bottom,
            'actions_selection_counter':
            getattr(self, 'actions_selection_counter', 0),
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(self.change_list_template or [
            'admin/%s/%s/change_list.html' %
            (self.model._meta.app_label, self.model._meta.object_name.lower()),
            'admin/%s/change_list.html' % self.model._meta.app_label,
            'admin/change_list.html'
        ],
                                  context,
                                  context_instance=context_instance)
Exemple #47
0
 def test_navbar_renders(self):
     t = Template('{% load pages_tags %}{% navbar %}')
     self.response = SimpleTemplateResponse(t)
     self.response.render()
     self.assertTrue(self.response.is_rendered)
 def get(request, team_identifier):
     context = {}
     context.update(csrf(request))
     return SimpleTemplateResponse(template='whiteboard_web/new_face_form.html', context=context)
Exemple #49
0
 def test_tag_renders(self):
     t = Template('{% load pages_tags %}{% get_page template="pages.basicpage" as page_list %}')
     response = SimpleTemplateResponse(t)
     response.render()
     self.assertTrue(response.is_rendered)
Exemple #50
0
def index(request):
    return SimpleTemplateResponse(template="index.html")
Exemple #51
0
 def test_args(self):
     response = SimpleTemplateResponse('', {}, 'application/json', 504)
     self.assertEqual(response['content-type'], 'application/json')
     self.assertEqual(response.status_code, 504)
Exemple #52
0
def plain_text_vision(request, pk):
    vision = Vision.objects.get(pk=pk)
    return SimpleTemplateResponse(template="plain_text_vision.txt", context={"vision": vision},
                                  content_type="text/plain")
Exemple #53
0
 def setUp(self):
     create_pages()
     t = Template('{% load pages_tags %}{% get_page "page-3" as page %}{% breadcrumbs %}')
     self.response = SimpleTemplateResponse(t)
Exemple #54
0
 def _render(self, template_name):
     response = SimpleTemplateResponse(
         template=template_name,
         context=self.get_context_data())
     response.render()
     return response.content.decode('utf-8')
Exemple #55
0
    def response_add(self, request, obj, post_url_continue=None):
        opts = obj._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)
        url_args = self.get_base_url_args(request)

        if "_saveasnew" in request.POST:
            url_args = url_args[:-1]

        obj_url = self.reverse_url('change', *url_args + [quote(pk_value)])

        if self.has_change_permission(request, obj):
            obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url),
                                   obj)
        else:
            obj_repr = force_text(obj)

        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': obj_repr,
        }

        if IS_POPUP_VAR in request.POST:
            to_field = request.POST.get(TO_FIELD_VAR)
            if to_field:
                attr = str(to_field)
            else:
                attr = obj._meta.pk.attname
            value = obj.serializable_value(attr)
            popup_response_data = json.dumps({
                'value': six.text_type(value),
                'obj': six.text_type(obj),
            })
            return SimpleTemplateResponse(
                'admin/popup_response.html', {
                    'popup_response_data': popup_response_data,
                })

        elif "_continue" in request.POST or (
                "_saveasnew" in request.POST and self.save_as_continue
                and self.has_change_permission(request, obj)):
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may edit it again below.'
                  ), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            if post_url_continue is None:
                post_url_continue = obj_url
            post_url_continue = self.add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, post_url_continue)
            return HttpResponseRedirect(post_url_continue)

        elif "_addanother" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may add another {name} below.'
                  ), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.path
            redirect_url = self.add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            msg = format_html(_('The {name} "{obj}" was added successfully.'),
                              **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            return self.response_post_save_add(request, obj)
Exemple #56
0
def inbound_users(request):

	rows = []

	header = ['ID', 'Email', 'Phone', 'Date Joined',
		 'Country', 'Referrer', 'Campaign',
		 'Created', 'Published', 'Plan', 'Pipedrive', 'Retentionmails', 'Pro Demo', 
		]

	days = int(request.GET.get('days', 14))
	date = datetime.date.today() - datetime.timedelta(days=days)


	#
	# Toggle pipedrive export
	#
	pipedrive_export = int(request.GET.get('pipedrive', -1))
	export_user_to_pipedrive(pipedrive_export)

	#
	# toggle retention
	#
	change_mail_settings = int(request.GET.get('retention', -1))
	change_mail_value = int(request.GET.get('value', -1))

	if change_mail_settings > 0:
		u = User.objects.get(pk=change_mail_settings)
		u.settings.receive_retention_emails = True if change_mail_value else False
		u.settings.save()

	if len(request.GET):
		return redirect(BASE_URL)

	# build row from user
	for user in User.objects.select_related('sales_info').select_related('settings').select_related('campaign_data').filter(date_joined__gte=date).order_by('-date_joined'):

		try:
			phone = user.settings.phone_number
		except:
			phone = ''

		# standard data
		row = [user.pk, user.username,  phone, user.date_joined.date()]

		# signup data
		try:
			row.extend([user.campaign_data.country, referral_link(user.campaign_data.referrer), user.campaign_data.name])
		except:
			row.extend(['', '', ''])

		user_videos = Video.objects.filter(team__owner=user)
		row.extend([user_videos.count(), user_videos.filter(published=True).count()]  )

		try:
			row.append(user.subscription.plan)
		except: 
			row.append('-')

		# pipedrive info
		try:
			url = PIPEDRIVE_PERSON_URL + str(user.sales_info.pipedrive_person_id)
			row.append('<a target = "_blank" href = "{0}">Linked</a>'.format(url))
		except:
			url = BASE_URL + '?pipedrive=' + str(user.pk)
			row.append('<a href = "{0}">Export</a>'.format(url))

		url = BASE_URL + '?retention=' + str(user.pk) +'&value=' + ('0' if user.settings.receive_retention_emails else '1')
		title = 'Enabled' if user.settings.receive_retention_emails else 'Disabled'
		row.append('<a href = "{0}">{1}</a>'.format(url, title))
		row.append('Upgrade (15 days)')




		rows.append(row)


	return SimpleTemplateResponse("insights/base.html", {
	    "title": "Inbound Users",
	    "insight_content": table(rows, header)
	    })
def view(request):

    #
    # General Query Building blocks
    #
    SELECT_PUBLISHED_REVISIONS = "SELECT COUNT(*) FROM videos_video as v JOIN videos_videorevision as vr ON(v.current_revision_id = vr.id) JOIN users_team as t ON (t.id = v.team_id) JOIN auth_user as u ON (u.id = t.owner_id) "
    SELECT_PUBLISHED_MARKERS = SELECT_PUBLISHED_REVISIONS + " JOIN videos_marker vm ON (vm.video_revision_id = vr.id)"
    SELECT_PUBLISHED_CONTENT_BLOCKS = SELECT_PUBLISHED_MARKERS + " JOIN videos_markercontent vmc ON (vmc.marker_id = vm.id)"
    SELECT_VIDEO_SOURCES = SELECT_PUBLISHED_REVISIONS + " JOIN videos_source as s ON (vr.source_id = s.id)"

    result = "Staff videos are not included in these statistics. <br />Only published videos are counted."

    #
    # Overall stats
    #
    result += helpers.header("Overall Stats (Published)")

    num_videos = get_result(SELECT_PUBLISHED_REVISIONS)
    num_markers = get_result(SELECT_PUBLISHED_MARKERS)
    num_blocks = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS)

    table = []
    table.append(["Published Videos", num_videos])
    table.append(["Published Markers", num_markers])
    table.append(["Published Content Blocks", num_blocks])
    table.append([""])
    table.append(["Markers per publ. Video", num_markers / num_videos])
    table.append(["Content Blocks per publ. Video", num_blocks / num_videos])
    table.append(["Content Blocks per publ. Marker", num_blocks / num_markers])
    result += helpers.table(table, ["Feature", "All", "Upgraded"])

    #
    # Import Source Stats
    #
    result += helpers.header("Import Source Stats (Published)")

    num_uploaded = get_result(SELECT_VIDEO_SOURCES +
                              " WHERE s.service like 'videopath'")

    num_youtube = get_result(SELECT_VIDEO_SOURCES +
                             " WHERE s.service like 'youtube'")
    num_vimeo = get_result(SELECT_VIDEO_SOURCES +
                           " WHERE s.service like 'vimeo'")
    num_wistia = get_result(SELECT_VIDEO_SOURCES +
                            " WHERE s.service like 'wistia'")
    num_brightcove = get_result(SELECT_VIDEO_SOURCES +
                                " WHERE s.service like 'brightcove'")

    table = [["Import Source", 'Videos']]
    table.append(["Uploaded Files", num_uploaded])
    table.append(["Youtube Hosting", num_youtube])
    table.append(["Vimeo Hosting", num_vimeo])
    table.append(["Wistia Hosting", num_wistia])
    table.append(["Brightcove Hosting", num_brightcove])
    result += helpers.chart(table, 'column')

    #
    # Video Feature Stats
    #
    result += helpers.header("Video Feature Stats (Published)")

    num_custom_colors = get_result(SELECT_PUBLISHED_REVISIONS +
                                   " WHERE vr.ui_color_1 != '#424242'")
    num_continuous_playback = get_result(
        SELECT_PUBLISHED_REVISIONS + " WHERE vr.continuous_playback = true")
    num_equal_marker_lengths = get_result(
        SELECT_PUBLISHED_REVISIONS + "WHERE vr.ui_equal_marker_lengths = true")
    num_custom_thumbnail = get_result(SELECT_PUBLISHED_REVISIONS +
                                      " WHERE vr.custom_thumbnail_id != 0")
    num_disable_share_buttons = get_result(
        SELECT_PUBLISHED_REVISIONS +
        " WHERE vr.ui_disable_share_buttons = true")
    num_fit_video = get_result(SELECT_PUBLISHED_REVISIONS +
                               " WHERE vr.ui_fit_video = true")
    num_custom_tracking_code = get_result(
        SELECT_PUBLISHED_REVISIONS + " WHERE vr.custom_tracking_code != ''")
    num_password = get_result(SELECT_PUBLISHED_REVISIONS +
                              " WHERE vr.password !=''")
    # num_iphone_enabled = get_result(SELECT_PUBLISHED_REVISIONS + " WHERE vr.iphone_images > 20")

    table = [['Feature', 'Videos']]
    table.append(["Custom Colors", num_custom_colors])
    table.append(["Custom Thumbnail", num_custom_thumbnail])
    table.append(["Disabled Share Buttons", num_disable_share_buttons])
    table.append(["Equal Marker Lengths", num_equal_marker_lengths])
    table.append(["Fit Video", num_fit_video])
    table.append(["Custom Tracking Code", num_custom_tracking_code])
    table.append(["Password Protection", num_password])
    table.append(["Continuous Playback", num_continuous_playback])
    # table.append(["Iphone enabled", num_iphone_enabled])
    result += helpers.chart(table, 'column')

    #
    # Content Block Stats
    #
    result += helpers.header("Content Block Stats (Published)")

    num_text_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                " WHERE vmc.type = 'text'")
    num_image_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                 " WHERE vmc.type = 'image'")
    num_social_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                  " WHERE vmc.type = 'social'")
    num_media_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                 " WHERE vmc.type = 'media'")
    num_website_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                   " WHERE vmc.type = 'website'")
    num_maps_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                " WHERE vmc.type = 'maps'")
    num_button_block = get_result(SELECT_PUBLISHED_CONTENT_BLOCKS +
                                  " WHERE vmc.type = 'simple_button'")

    table = [["Type", "Amount"]]
    table.append(["Text ", num_text_block])
    table.append(["Image ", num_image_block])
    table.append(["Social ", num_social_block])
    table.append(["Media ", num_media_block])
    table.append(["Website ", num_website_block])
    table.append(["Button ", num_button_block])
    table.append(["Maps ", num_maps_block])
    result += helpers.chart(table, 'pie')

    return SimpleTemplateResponse("insights/base.html", {
        "title": "Features",
        "insight_content": result
    })
Exemple #58
0
    def response_change(self, request, obj):
        if IS_POPUP_VAR in request.POST:
            to_field = request.POST.get(TO_FIELD_VAR)
            attr = str(to_field) if to_field else obj._meta.pk.attname
            value = request.resolver_match.args[0]
            new_value = obj.serializable_value(attr)
            popup_response_data = json.dumps({
                'action':
                'change',
                'value':
                six.text_type(value),
                'obj':
                six.text_type(obj),
                'new_value':
                six.text_type(new_value),
            })
            return SimpleTemplateResponse(
                'admin/popup_response.html', {
                    'popup_response_data': popup_response_data,
                })

        opts = self.model._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': format_html('<a href="{}">{}</a>', urlquote(request.path),
                               obj),
        }
        if "_continue" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully. You may edit it again below.'
                  ), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.path
            redirect_url = self.add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_saveasnew" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may edit it again below.'
                  ), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = self.reverse_url('change',
                                            *self.get_base_url_args(request))
            redirect_url = self.add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_addanother" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully. You may add another {name} below.'
                  ), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = self.reverse_url(
                'add',
                *self.get_base_url_args(request)[:-1])
            redirect_url = self.add_preserved_filters(
                {
                    'preserved_filters': preserved_filters,
                    'opts': opts
                }, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully.'), **msg_dict)
            self.message_user(request, msg, messages.SUCCESS)
        return self.response_post_save_change(request, obj)
Exemple #59
0
 def get(self, request):
     return SimpleTemplateResponse('MainContent.html')
Exemple #60
0
def handle_index(request):
    print request.user
    if request.user is None:
        return SimpleTemplateResponse("index.html")
    else:
        return redirect('/navigate/')