Exemplo n.º 1
0
 def get_json_export(self, context):
     results = self._get_objects(context)
     return json.dumps(
         {'objects': results},
         ensure_ascii=False,
         indent=(self.request.GET.get('export_json_format', 'off') == 'on')
         and 4 or None)
Exemplo n.º 2
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    item['menus'] = [filter_item(
                        i) for i in item['menus'] if check_menu_permission(i)]
                return item

            nav_menu = [filter_item(item) for item in menus if check_menu_permission(item)]
            nav_menu = filter(lambda i: bool(i['menus']), nav_menu)

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected
        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title or _(u'Django Xadmin'),
            'site_footer': self.site_footer or _(u'my-company.inc 2013'),
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 3
0
    def block_top_navmenu(self, context, nodes):

        themes = [{'name': _(u"Default"), 'description': _(
            u"Default bootstrap theme"), 'css': self.default_theme},
            {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"),
            'css': self.bootstrap2_theme}]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    h = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
                    resp, content = h.request("http://bootswatch.com/api/3.json", 'GET', \
                        "", headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']})
                    watch_themes = json.loads(content)['themes']
                    ex_themes.extend([
                        {'name': t['name'], 'description': t['description'],
                            'css': t['cssMin'], 'thumbnail': t['thumbnail']}
                        for t in watch_themes])
                except Exception, e:
                    print e

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)
Exemplo n.º 4
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {'name': _(u"Default"), 'description': _(u"Default bootstrap theme"), 'css': self.default_theme},
            {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"), 'css': self.bootstrap2_theme},
            ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    h = httplib2.Http()
                    resp, content = h.request("https://bootswatch.com/api/3.json", 'GET', '',
                        headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']})
                    if six.PY3:
                        content = content.decode()
                    watch_themes = json.loads(content)['themes']
                    ex_themes.extend([
                        {'name': t['name'], 'description': t['description'],
                            'css': t['cssMin'], 'thumbnail': t['thumbnail']}
                        for t in watch_themes])
                except Exception as e:
                    print(e)

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(loader.render_to_string('xadmin/blocks/comm.top.theme.html', {'themes': themes, 'select_css': select_css}))
Exemplo n.º 5
0
    def get(self, request, *args, **kwargs):
        from django.contrib.gis import geos

        field = kwargs['field']
        x1 = request.GET.get('x1', None)
        y1 = request.GET.get('y1', None)
        x2 = request.GET.get('x2', None)
        y2 = request.GET.get('y2', None)
        content = []

        bbox = (x1, y1, x2, y2)
        geom = geos.Polygon.from_bbox(bbox)
        qargs = { '%s__intersects' % field: geom, }
        queryset = self.model.gis.filter( **qargs )
        name_for_map = self.model._meta.get_field(field).name_for_map
        for item in queryset:
            location = getattr(item, field)
            data = {'lon': location.coords[0], 'lat': location.coords[1], 'name': item.name};
            if name_for_map:
                name_for_map_value = getattr(item, name_for_map)
                if callable(name_for_map_value):
                    data['name'] = name_for_map_value()
                else:
                    data['name'] = name_for_map_value
            else:
                data['name'] = ''
            content.append(data);

        response = HttpResponse(content_type="application/json; charset=UTF-8")
        response.write(
            json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
        return response
Exemplo n.º 6
0
    def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart['x-field']
        y_fields = self.chart['y-field']
        self.y_fields = (y_fields, ) if type(y_fields) not in (
            list, tuple) else y_fields

        datas = [{
            "data": [],
            "label":
            force_text(label_for_field(i, self.model, model_admin=self))
        } for i in self.y_fields]

        self.make_result_list()

        for obj in self.result_list:
            xf, attrs, value = lookup_field(self.x_field, obj, self)
            for i, yfname in enumerate(self.y_fields):
                yf, yattrs, yv = lookup_field(yfname, obj, self)
                datas[i]["data"].append((value, yv))

        option = {
            'series': {
                'lines': {
                    'show': True
                },
                'points': {
                    'show': False
                }
            },
            'grid': {
                'hoverable': True,
                'clickable': True
            }
        }
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (models.DateTimeField, models.DateField,
                                models.TimeField):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is models.DateField:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get('option', {}))

        content = {'data': datas, 'option': option}

        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)
        # print(result)
        return HttpResponse(result)
Exemplo n.º 7
0
 def render_response(self, content, response_type='json'):
     if response_type == 'json':
         response = HttpResponse(content_type="application/json; charset=UTF-8")
         response.write(
             json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
         return response
     return HttpResponse(content)
Exemplo n.º 8
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {'name': _(u"Default"), 'description': _(u"Default bootstrap theme"), 'css': self.default_theme},
            {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"), 'css': self.bootstrap2_theme},
        ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    h = httplib2.Http()
                    resp, content = h.request("https://bootswatch.com/api/3.json", 'GET', '',
                                              headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']})
                    if six.PY3:
                        content = content.decode()
                    watch_themes = json.loads(content)['themes']
                    ex_themes.extend([
                        {'name': t['name'], 'description': t['description'],
                            'css': t['cssMin'], 'thumbnail': t['thumbnail']}
                        for t in watch_themes])
                except Exception as e:
                    print(e)

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(loader.render_to_string('xadmin/blocks/comm.top.theme.html', {'themes': themes, 'select_css': select_css}))
Exemplo n.º 9
0
    def get(self, request, name):
        if name not in self.data_dict_charts:
            return HttpResponseNotFound()

        self.chart = self.data_dict_charts[name]
        self.x_field_name = self.chart.get('x-field-name')
        self.y_field_name = self.chart.get('x-field-name')
        self.x_ticks = self.chart.get('x-ticks')
        self.y_ticks = self.chart.get('y-ticks')

        datas = self.chart['datas']
        option = {
            'series': {'lines': {'show': True}, 'points': {'show': True}},
            'grid': {'hoverable': True, 'clickable': True},
        }

        try:
            xfield = datas[0].get('data')[0][0]
            if type(xfield) in (datetime.datetime, datetime.date, datetime.time):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is datetime.date:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is datetime.time:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    if xfield.hour == 0 and xfield.minute == 0 and xfield.second == 0:
                        option['xaxis']['timeformat'] = "%y/%m/%d"
                    else:
                        option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass
        content = {'data': datas, 'option': option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)
        return HttpResponse(result)
Exemplo n.º 10
0
    def block_top_navmenu(self, context, nodes):

        themes = [{'name': _(u"Default"), 'description': _(
            u"Default bootstrap theme"), 'css': self.default_theme},
            {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"),
            'css': self.bootstrap2_theme}]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    watch_themes = json.loads(urllib.urlopen(
                        'http://api.bootswatch.com/3/').read())['themes']
                    ex_themes.extend([
                        {'name': t['name'], 'description': t['description'],
                            'css': t['cssMin'], 'thumbnail': t['thumbnail']}
                        for t in watch_themes])
                except Exception:
                    pass

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(loader.render_to_string('xadmin/blocks/comm.top.theme.html', {'themes': themes, 'select_css': select_css}))
Exemplo n.º 11
0
 def render_response(self, content, response_type='json'):
     if response_type == 'json':
         response = HttpResponse(content_type="application/json; charset=UTF-8")
         response.write(
             json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
         return response
     return HttpResponse(content)
Exemplo n.º 12
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    item['menus'] = [filter_item(
                        i) for i in item['menus'] if check_menu_permission(i)]
                return item

            nav_menu = [filter_item(item) for item in menus if check_menu_permission(item)]
            nav_menu = filter(lambda i: bool(i['menus']), nav_menu)

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected
        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title or _(u'SoftMachine'),
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 13
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {
                "name": _(u"Default"),
                "description": _(u"Default bootstrap theme"),
                "css": self.default_theme,
            },
            {
                "name": _(u"Bootstrap2"),
                "description": _(u"Bootstrap 2.x theme"),
                "css": self.bootstrap2_theme,
            },
        ]
        select_css = context.get("site_theme", self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    h = httplib2.Http()
                    resp, content = h.request(
                        "http://bootswatch.com/api/3.json",
                        "GET",
                        "",
                        headers={
                            "Accept": "application/json",
                            "User-Agent": self.request.META["HTTP_USER_AGENT"],
                        },
                    )
                    if six.PY3:
                        content = content.decode()
                    watch_themes = json.loads(content)["themes"]
                    ex_themes.extend([{
                        "name": t["name"],
                        "description": t["description"],
                        "css": t["cssMin"],
                        "thumbnail": t["thumbnail"],
                    } for t in watch_themes])
                except Exception as e:
                    print(e)

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string(
                "xadmin/blocks/comm.top.theme.html",
                {
                    "themes": themes,
                    "select_css": select_css
                },
            ))
Exemplo n.º 14
0
 def get_json_export(self, context):
     results = self._get_objects(context)
     return json.dumps(
         {"objects": results},
         ensure_ascii=False,
         indent=(self.request.GET.get("export_json_format", "off") == "on")
         and 4 or None,
     )
Exemplo n.º 15
0
    def block_top_navmenu(self, context, nodes):

        themes = [{
            'name': _(u"Default"),
            'description': _(u"Default bootstrap theme"),
            'css': self.default_theme
        }, {
            'name': _(u"Bootstrap2"),
            'description': _(u"Bootstrap 2.x theme"),
            'css': self.bootstrap2_theme
        }]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    flag = False  # 假如为True使用原来的代码,假如为Flase,使用requests库来访问
                    if flag:
                        h = httplib2.Http()
                        resp, content = h.request(
                            "http://bootswatch.com/api/3.json",
                            'GET',
                            '',
                            headers={
                                "Accept": "application/json",
                                "User-Agent":
                                self.request.META['HTTP_USER_AGENT']
                            })
                        if six.PY3:
                            content = content.decode()
                        watch_themes = json.loads(content)['themes']
                    else:
                        content = requests.get(
                            "https://bootswatch.com/api/3.json")
                        # if six.PY3:
                        #     content = content.text.decode()
                        watch_themes = json.loads(content.text)['themes']

                    ex_themes.extend([{
                        'name': t['name'],
                        'description': t['description'],
                        'css': t['cssMin'],
                        'thumbnail': t['thumbnail']
                    } for t in watch_themes])
                except Exception, e:
                    print e

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)
Exemplo n.º 16
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    item['menus'] = [
                        filter_item(i) for i in item['menus']
                        if check_menu_permission(i)
                    ]
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = filter(lambda i: bool(i['menus']), nav_menu)

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = 'url' in menu and path.startswith(menu['url']) or False
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context['nav_menu'] = nav_menu
        context['site_title'] = self.site_title or _(u'Django Xadmin')

        return context
Exemplo n.º 17
0
 def render_response(self, content, response_type='json'):
     """
     便捷方法,方便生成 HttpResponse,如果 response_type 为 ``json`` 会自动转为 json 格式后输出
     """
     if response_type == 'json':
         response = HttpResponse(
             content_type="application/json; charset=UTF-8")
         response.write(
             json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
         return response
     return HttpResponse(content)
Exemplo n.º 18
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    item['menus'] = [filter_item(
                        i) for i in item['menus'] if check_menu_permission(i)]
                return item

            nav_menu = [filter_item(
                item) for item in menus if check_menu_permission(item)]
            nav_menu = filter(lambda i: bool(i['menus']), nav_menu)

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = 'url' in menu and path.startswith(menu['url']) or False
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected
        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context['nav_menu'] = nav_menu
        context['site_title'] = self.site_title or _(u'Django Xadmin')

        return context
Exemplo n.º 19
0
    def block_top_navmenu(self, context, nodes):

        themes = [{
            'name': _(u"Default"),
            'description': _(u"Default bootstrap theme"),
            'css': self.default_theme
        }, {
            'name': _(u"Bootstrap2"),
            'description': _(u"Bootstrap 2.x theme"),
            'css': self.bootstrap2_theme
        }]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    import requests
                    watch_themes = json.loads(
                        requests.get(
                            'http://api.bootswatch.com/3/').text)['themes']
                    ex_themes.extend([{
                        'name': t['name'],
                        'description': t['description'],
                        'css': t['cssMin'],
                        'thumbnail': t['thumbnail']
                    } for t in watch_themes
                                      if t['name'] not in ('Cosmo', 'Cyborg',
                                                           'Darkly')])
                except Exception:
                    pass

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string(
                'xadmin/blocks/comm.top.theme.html', {
                    'themes': themes,
                    'select_css': select_css,
                    'head_fix': self.admin_site.head_fix
                }))
Exemplo n.º 20
0
    def get(self, request, *args, **kwargs):
        from xadmin.filters import SEARCH_VAR
        query = self.request.GET.get(SEARCH_VAR, '')
        field = kwargs['field']

        if query:
            qargs = { field+'__startswith': query, }
            queryset = self.model._default_manager.filter( **qargs ).values(field).distinct()
            content = {'options': [v[field] for v in queryset[:self.MAX_HINTS]], }
        else:
            content = []

        response = HttpResponse(content_type="application/json; charset=UTF-8")
        response.write(
            json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
        return response
Exemplo n.º 21
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {
                'name': _(u"Default"),
                'description': _(u"Default bootstrap theme"),
                'css': self.default_theme
            },
            {
                'name': _(u"Bootstrap2"),
                'description': _(u"Bootstrap 2.x theme"),
                'css': self.bootstrap2_theme
            },
        ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    watch_themes = json.loads(
                        urllib.urlopen(
                            'http://api.bootswatch.com/3/').read())['themes']
                    ex_themes.extend([{
                        'name': t['name'],
                        'description': t['description'],
                        'css': t['cssMin'],
                        'thumbnail': t['thumbnail']
                    } for t in watch_themes])
                except Exception:
                    pass

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.theme.html', {
                'themes': themes,
                'select_css': select_css
            }))
Exemplo n.º 22
0
    def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart['x-field']
        y_fields = self.chart['y-field']
        self.y_fields = (
            y_fields,) if type(y_fields) not in (list, tuple) else y_fields

        datas = [{"data":[], "label": force_text(label_for_field(
            i, self.model, model_admin=self))} for i in self.y_fields]

        self.make_result_list()

        for obj in self.result_list:
            xf, attrs, value = lookup_field(self.x_field, obj, self)
            for i, yfname in enumerate(self.y_fields):
                yf, yattrs, yv = lookup_field(yfname, obj, self)
                datas[i]["data"].append((value, yv))

        option = {'series': {'lines': {'show': True}, 'points': {'show': False}},
                  'grid': {'hoverable': True, 'clickable': True}}
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (models.DateTimeField, models.DateField, models.TimeField):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is models.DateField:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get('option', {}))

        content = {'data': datas, 'option': option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)

        return HttpResponse(result)
Exemplo n.º 23
0
    def get(self, request, *args, **kwargs):
        from xadmin.filters import SEARCH_VAR
        query = self.request.GET.get(SEARCH_VAR, '')
        field = kwargs['field']

        if query:
            if 'django.contrib.postgres' in settings.INSTALLED_APPS:
                key = '__unaccent'
            else:
                key = ''

            qargs = { '%s%s__istartswith' % (field, key): query, }
            queryset = self.model._default_manager.filter( **qargs ).values(field) #.distinct()
            content = {'options': [v[field] for v in queryset[:self.MAX_HINTS]], }
        else:
            content = []

        response = HttpResponse(content_type="application/json; charset=UTF-8")
        response.write(
            json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
        return response
Exemplo n.º 24
0
    def block_top_navmenu(self, context, nodes):

        themes = [{
            'name': _(u"Default"),
            'description': _(u"Default bootstrap theme"),
            'css': self.default_theme
        }, {
            'name': _(u"Bootstrap2"),
            'description': _(u"Bootstrap 2.x theme"),
            'css': self.bootstrap2_theme
        }]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    h = httplib2.Http(".cache",
                                      disable_ssl_certificate_validation=True)
                    resp, content = h.request("http://bootswatch.com/api/3.json", 'GET', \
                        "", headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']})
                    watch_themes = json.loads(content)['themes']
                    ex_themes.extend([{
                        'name': t['name'],
                        'description': t['description'],
                        'css': t['cssMin'],
                        'thumbnail': t['thumbnail']
                    } for t in watch_themes])
                except Exception, e:
                    print e

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)
Exemplo n.º 25
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {"name": _(u"Default Theme"), "description": _(u"default bootstrap theme"), "css": self.default_theme}
        ]
        select_css = context.get("site_theme", self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    watch_themes = json.loads(urllib.urlopen("http://api.bootswatch.com/").read())["themes"]
                    ex_themes.extend(
                        [
                            {
                                "name": t["name"],
                                "description": t["description"],
                                "css": t["css-min"],
                                "thumbnail": t["thumbnail"],
                            }
                            for t in watch_themes
                        ]
                    )
                except Exception:
                    pass

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string("xadmin/blocks/comm.top.theme.html", {"themes": themes, "select_css": select_css})
        )
Exemplo n.º 26
0
    def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart['x-field']
        y_fields = self.chart['y-field']
        self.y_fields = (
            y_fields,) if type(y_fields) not in (list, tuple) else y_fields

        if not hasattr(self, 'get_%s_chart_data' % name):
            datas = self.get_model_data()
        else:
            datas = getattr(self, 'get_%s_chart_data' % name)()
        option = {
            'series': {'lines': {'show': True}, 'points': {'show': True}},
            'grid': {'hoverable': True, 'clickable': True}}
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (models.DateTimeField, models.DateField, models.TimeField):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is models.DateField:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get('option', {}))

        content = {'data': datas, 'option': option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)

        return HttpResponse(result)
Exemplo n.º 27
0
 def get_json_export(self, context):
     results = self._get_objects(context)
     return json.dumps({'objects': results}, ensure_ascii=False,
                       indent=(self._options_is_on('export_json_format') and 4 or None))
Exemplo n.º 28
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {
                'name': _(u"Default"),
                'description': _(u"Default bootstrap theme"),
                'css': self.default_theme
            },
            {
                'name': _(u"Bootstrap2"),
                'description': _(u"Bootstrap 2.x theme"),
                'css': self.bootstrap2_theme
            },
        ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    if six.PY3:
                        #官方通过爬虫获取content,问题:登录时间长。改进:将爬虫结果直接写在这里。2019.12.30
                        content = {
                            "version":
                            "3.4.1",
                            "themes": [{
                                "name":
                                "Cerulean",
                                "description":
                                "A calm blue sky",
                                "thumbnail":
                                "https://bootswatch.com/3/cerulean/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/cerulean/",
                                "css":
                                "https://bootswatch.com/3/cerulean/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/cerulean/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cerulean/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/cerulean/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/cerulean/variables.less",
                                "scss":
                                "https://bootswatch.com/3/cerulean/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/cerulean/_variables.scss"
                            }, {
                                "name":
                                "Cosmo",
                                "description":
                                "An ode to Metro",
                                "thumbnail":
                                "https://bootswatch.com/3/cosmo/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/cosmo/",
                                "css":
                                "https://bootswatch.com/3/cosmo/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/cosmo/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/cosmo/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/cosmo/variables.less",
                                "scss":
                                "https://bootswatch.com/3/cosmo/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/cosmo/_variables.scss"
                            }, {
                                "name":
                                "Cyborg",
                                "description":
                                "Jet black and electric blue",
                                "thumbnail":
                                "https://bootswatch.com/3/cyborg/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/cyborg/",
                                "css":
                                "https://bootswatch.com/3/cyborg/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/cyborg/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cyborg/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/cyborg/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/cyborg/variables.less",
                                "scss":
                                "https://bootswatch.com/3/cyborg/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/cyborg/_variables.scss"
                            }, {
                                "name":
                                "Darkly",
                                "description":
                                "Flatly in night mode",
                                "thumbnail":
                                "https://bootswatch.com/3/darkly/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/darkly/",
                                "css":
                                "https://bootswatch.com/3/darkly/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/darkly/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/darkly/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/darkly/variables.less",
                                "scss":
                                "https://bootswatch.com/3/darkly/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/darkly/_variables.scss"
                            }, {
                                "name":
                                "Flatly",
                                "description":
                                "Flat and modern",
                                "thumbnail":
                                "https://bootswatch.com/3/flatly/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/flatly/",
                                "css":
                                "https://bootswatch.com/3/flatly/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/flatly/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/flatly/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/flatly/variables.less",
                                "scss":
                                "https://bootswatch.com/3/flatly/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/flatly/_variables.scss"
                            }, {
                                "name":
                                "Journal",
                                "description":
                                "Crisp like a new sheet of paper",
                                "thumbnail":
                                "https://bootswatch.com/3/journal/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/journal/",
                                "css":
                                "https://bootswatch.com/3/journal/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/journal/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/journal/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/journal/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/journal/variables.less",
                                "scss":
                                "https://bootswatch.com/3/journal/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/journal/_variables.scss"
                            }, {
                                "name":
                                "Lumen",
                                "description":
                                "Light and shadow",
                                "thumbnail":
                                "https://bootswatch.com/3/lumen/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/lumen/",
                                "css":
                                "https://bootswatch.com/3/lumen/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/lumen/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/lumen/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/lumen/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/lumen/variables.less",
                                "scss":
                                "https://bootswatch.com/3/lumen/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/lumen/_variables.scss"
                            }, {
                                "name":
                                "Paper",
                                "description":
                                "Material is the metaphor",
                                "thumbnail":
                                "https://bootswatch.com/3/paper/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/paper/",
                                "css":
                                "https://bootswatch.com/3/paper/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/paper/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/paper/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/paper/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/paper/variables.less",
                                "scss":
                                "https://bootswatch.com/3/paper/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/paper/_variables.scss"
                            }, {
                                "name":
                                "Readable",
                                "description":
                                "Optimized for legibility",
                                "thumbnail":
                                "https://bootswatch.com/3/readable/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/readable/",
                                "css":
                                "https://bootswatch.com/3/readable/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/readable/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/readable/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/readable/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/readable/variables.less",
                                "scss":
                                "https://bootswatch.com/3/readable/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/readable/_variables.scss"
                            }, {
                                "name":
                                "Sandstone",
                                "description":
                                "A touch of warmth",
                                "thumbnail":
                                "https://bootswatch.com/3/sandstone/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/sandstone/",
                                "css":
                                "https://bootswatch.com/3/sandstone/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/sandstone/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/sandstone/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/sandstone/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/sandstone/variables.less",
                                "scss":
                                "https://bootswatch.com/3/sandstone/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/sandstone/_variables.scss"
                            }, {
                                "name":
                                "Simplex",
                                "description":
                                "Mini and minimalist",
                                "thumbnail":
                                "https://bootswatch.com/3/simplex/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/simplex/",
                                "css":
                                "https://bootswatch.com/3/simplex/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/simplex/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/simplex/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/simplex/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/simplex/variables.less",
                                "scss":
                                "https://bootswatch.com/3/simplex/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/simplex/_variables.scss"
                            }, {
                                "name":
                                "Slate",
                                "description":
                                "Shades of gunmetal gray",
                                "thumbnail":
                                "https://bootswatch.com/3/slate/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/slate/",
                                "css":
                                "https://bootswatch.com/3/slate/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/slate/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/slate/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/slate/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/slate/variables.less",
                                "scss":
                                "https://bootswatch.com/3/slate/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/slate/_variables.scss"
                            }, {
                                "name":
                                "Spacelab",
                                "description":
                                "Silvery and sleek",
                                "thumbnail":
                                "https://bootswatch.com/3/spacelab/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/spacelab/",
                                "css":
                                "https://bootswatch.com/3/spacelab/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/spacelab/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/spacelab/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/spacelab/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/spacelab/variables.less",
                                "scss":
                                "https://bootswatch.com/3/spacelab/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/spacelab/_variables.scss"
                            }, {
                                "name":
                                "Superhero",
                                "description":
                                "The brave and the blue",
                                "thumbnail":
                                "https://bootswatch.com/3/superhero/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/superhero/",
                                "css":
                                "https://bootswatch.com/3/superhero/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/superhero/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/superhero/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/superhero/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/superhero/variables.less",
                                "scss":
                                "https://bootswatch.com/3/superhero/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/superhero/_variables.scss"
                            }, {
                                "name":
                                "United",
                                "description":
                                "Ubuntu orange and unique font",
                                "thumbnail":
                                "https://bootswatch.com/3/united/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/united/",
                                "css":
                                "https://bootswatch.com/3/united/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/united/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/united/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/united/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/united/variables.less",
                                "scss":
                                "https://bootswatch.com/3/united/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/united/_variables.scss"
                            }, {
                                "name":
                                "Yeti",
                                "description":
                                "A friendly foundation",
                                "thumbnail":
                                "https://bootswatch.com/3/yeti/thumbnail.png",
                                "preview":
                                "https://bootswatch.com/3/yeti/",
                                "css":
                                "https://bootswatch.com/3/yeti/bootstrap.css",
                                "cssMin":
                                "https://bootswatch.com/3/yeti/bootstrap.min.css",
                                "cssCdn":
                                "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/yeti/bootstrap.min.css",
                                "less":
                                "https://bootswatch.com/3/yeti/bootswatch.less",
                                "lessVariables":
                                "https://bootswatch.com/3/yeti/variables.less",
                                "scss":
                                "https://bootswatch.com/3/yeti/_bootswatch.scss",
                                "scssVariables":
                                "https://bootswatch.com/3/yeti/_variables.scss"
                            }]
                        }

                    watch_themes = content['themes']
                    ex_themes.extend([{
                        'name': t['name'],
                        'description': t['description'],
                        'css': t['cssMin'],
                        'thumbnail': t['thumbnail']
                    } for t in watch_themes])
                except Exception as e:
                    print(e)

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.theme.html', {
                'themes': themes,
                'select_css': select_css
            }))
Exemplo n.º 29
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    before_filter_length = len(item['menus'])
                    item['menus'] = [filter_item(
                        i) for i in item['menus'] if check_menu_permission(i)]
                    after_filter_length = len(item['menus'])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [filter_item(item) for item in menus if check_menu_permission(item)]
            nav_menu = list(filter(lambda x:x, nav_menu))

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu, cls=JSONEncoder, ensure_ascii=False)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected
        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title,
            'site_footer': self.site_footer,
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 30
0
    def get_context(self):
        """
        **Context Params** :
            ``site_title`` : 使用 :attr:`site_title` 属性,默认为 "Django Xadmin"
            ``nav_menu`` : 权限过滤后的系统菜单项,如果在非 DEBUG 模式,该项会缓存在 SESSION 中
        """
        context = super(CommAdminView, self).get_context()
        # DEBUG模式会首先尝试从SESSION中取得缓存的菜单项
        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':  # perm项如果为 ``super`` 说明需要超级用户权限
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    before_filter_length = len(item['menus'])
                    item['menus'] = [
                        filter_item(i) for i in item['menus']
                        if check_menu_permission(i)
                    ]
                    after_filter_length = len(item['menus'])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = list(filter(lambda x: x, nav_menu))

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(
                    nav_menu, cls=JSONEncoder, ensure_ascii=False)
                self.request.session.modified = True

        def check_selected(menu, path):
            # 判断菜单项是否被选择,使用当前url跟菜单项url对比
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title,
            'site_footer': self.site_footer,
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 31
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {
                'name': _(u"Default"),
                'description': _(u"Default bootstrap theme"),
                'css': self.default_theme
            },
            {
                'name': _(u"Bootstrap2"),
                'description': _(u"Bootstrap 2.x theme"),
                'css': self.bootstrap2_theme
            },
        ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                flag = False  # 假如为True使用原来的代码,假如为Flase,使用requests库来访问
                url_bootswath = "https://bootswatch.com/api/3.json"
                header1 = {
                    "Accept": "application/json",
                    "User-Agent": self.request.META['HTTP_USER_AGENT']
                }
                headers2 = {
                    'content-type': 'application/json',
                    "accept":
                    "text / html, application / xhtml + xml, application / xml;q = 0.9, image / webp, image / apng, * / *;q = 0.8",
                    "accept-encoding": "gzip, deflate, br",
                    "User-Agent":
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
                    "upgrade-insecure-requests": "1",
                }
                ck = "__cfduid=d13ae6de34090a59037f21e453bbc267a1526834776; cf_clearance=10fff22cb373a1c8b10204b489658f34b0c9ad8d-1526834783-3600; __utma=97413516.806424570.1526835277.1526835277.1526835277.1; __utmc=97413516; __utmz=97413516.1526835277.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utmb=97413516.2.10.1526835277"
                cookies = {}
                for line in ck.split(';'):
                    name, value = line.strip().split('=', 1)
                    cookies[name] = value  # 为字典cookies添加内容

                watch_themes = []
                try:
                    if flag:
                        h = httplib2.Http()
                        resp, content = h.request(url_bootswath,
                                                  'GET',
                                                  '',
                                                  headers=headers2)
                        if six.PY3:
                            content = content.decode()
                        watch_themes = json.loads(content)['themes']
                    else:
                        session = requests.Session()

                        content = session.get(url_bootswath,
                                              cookies=cookies,
                                              headers=headers2,
                                              verify=False)
                        if six.PY3:
                            if not isinstance(content.text, str):
                                content = content.text.decode()
                        watch_themes = json.loads(content.text)['themes']

                except Exception as e:
                    jsonFile = os.path.join(
                        os.path.dirname(os.path.realpath(__file__)),
                        'themes3.json')
                    with open(jsonFile, 'r') as f:
                        watch_themes = json.loads(f.read())['themes']
                ex_themes.extend([{
                    'name': t['name'],
                    'description': t['description'],
                    'css': t['cssMin'],
                    'thumbnail': t['thumbnail']
                } for t in watch_themes])

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.theme.html', {
                'themes': themes,
                'select_css': select_css
            }))
Exemplo n.º 32
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    before_filter_length = len(item['menus'])
                    item['menus'] = [
                        filter_item(i) for i in item['menus']
                        if check_menu_permission(i)
                    ]
                    after_filter_length = len(item['menus'])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = list(filter(lambda x: x, nav_menu))

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(
                    nav_menu, cls=JSONEncoder, ensure_ascii=False)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title,
            'site_footer': self.site_footer,
            'site_logo': self.site_logo,
            'onlyLog': self.onlyLog,
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 33
0
    def block_top_navmenu(self, context, nodes):

        themes = [
            {'name': _(u"Default"), 'description': _(u"Default bootstrap theme"), 'css': self.default_theme},
            {'name': _(u"Bootstrap2"), 'description': _(u"Bootstrap 2.x theme"), 'css': self.bootstrap2_theme},
            ]
        select_css = context.get('site_theme', self.default_theme)

        if self.user_themes:
            themes.extend(self.user_themes)

        if self.use_bootswatch:
            ex_themes = cache.get(THEME_CACHE_KEY)
            if ex_themes:
                themes.extend(json.loads(ex_themes))
            else:
                ex_themes = []
                try:
                    flag = False  # 假如为True使用原来的代码,假如为Flase,使用requests库来访问
                    if flag:
                        h = httplib2.Http()
                        resp, content = h.request("https://bootswatch.com/api/3.json", 'GET', '',
                            headers={"Accept": "application/json", "User-Agent": self.request.META['HTTP_USER_AGENT']})
                        if six.PY3:
                            content = content.decode()
                        watch_themes = json.loads(content)['themes']
                    else:
                        # content = requests.get("https://bootswatch.com/api/3.json", verify=False)
                        # if six.PY3:
                        #     content = content.text.decode()
                        # watch_themes = json.loads(content.text)['themes']
                        watch_themes = {
                            "themes": [
                                {
                                    "name": "Cerulean",
                                    "description": "A calm blue sky",
                                    "thumbnail": "https://bootswatch.com/3/cerulean/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/cerulean/",
                                    "css": "https://bootswatch.com/3/cerulean/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/cerulean/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cerulean/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/cerulean/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/cerulean/variables.less",
                                    "scss": "https://bootswatch.com/3/cerulean/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/cerulean/_variables.scss"
                                },
                                {
                                    "name": "Cosmo",
                                    "description": "An ode to Metro",
                                    "thumbnail": "https://bootswatch.com/3/cosmo/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/cosmo/",
                                    "css": "https://bootswatch.com/3/cosmo/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/cosmo/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/cosmo/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/cosmo/variables.less",
                                    "scss": "https://bootswatch.com/3/cosmo/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/cosmo/_variables.scss"
                                },
                                {
                                    "name": "Cyborg",
                                    "description": "Jet black and electric blue",
                                    "thumbnail": "https://bootswatch.com/3/cyborg/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/cyborg/",
                                    "css": "https://bootswatch.com/3/cyborg/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/cyborg/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cyborg/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/cyborg/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/cyborg/variables.less",
                                    "scss": "https://bootswatch.com/3/cyborg/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/cyborg/_variables.scss"
                                },
                                {
                                    "name": "Darkly",
                                    "description": "Flatly in night mode",
                                    "thumbnail": "https://bootswatch.com/3/darkly/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/darkly/",
                                    "css": "https://bootswatch.com/3/darkly/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/darkly/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/darkly/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/darkly/variables.less",
                                    "scss": "https://bootswatch.com/3/darkly/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/darkly/_variables.scss"
                                },
                                {
                                    "name": "Flatly",
                                    "description": "Flat and modern",
                                    "thumbnail": "https://bootswatch.com/3/flatly/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/flatly/",
                                    "css": "https://bootswatch.com/3/flatly/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/flatly/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/flatly/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/flatly/variables.less",
                                    "scss": "https://bootswatch.com/3/flatly/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/flatly/_variables.scss"
                                },
                                {
                                    "name": "Journal",
                                    "description": "Crisp like a new sheet of paper",
                                    "thumbnail": "https://bootswatch.com/3/journal/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/journal/",
                                    "css": "https://bootswatch.com/3/journal/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/journal/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/journal/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/journal/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/journal/variables.less",
                                    "scss": "https://bootswatch.com/3/journal/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/journal/_variables.scss"
                                },
                                {
                                    "name": "Lumen",
                                    "description": "Light and shadow",
                                    "thumbnail": "https://bootswatch.com/3/lumen/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/lumen/",
                                    "css": "https://bootswatch.com/3/lumen/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/lumen/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/lumen/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/lumen/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/lumen/variables.less",
                                    "scss": "https://bootswatch.com/3/lumen/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/lumen/_variables.scss"
                                },
                                {
                                    "name": "Paper",
                                    "description": "Material is the metaphor",
                                    "thumbnail": "https://bootswatch.com/3/paper/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/paper/",
                                    "css": "https://bootswatch.com/3/paper/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/paper/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/paper/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/paper/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/paper/variables.less",
                                    "scss": "https://bootswatch.com/3/paper/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/paper/_variables.scss"
                                },
                                {
                                    "name": "Readable",
                                    "description": "Optimized for legibility",
                                    "thumbnail": "https://bootswatch.com/3/readable/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/readable/",
                                    "css": "https://bootswatch.com/3/readable/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/readable/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/readable/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/readable/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/readable/variables.less",
                                    "scss": "https://bootswatch.com/3/readable/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/readable/_variables.scss"
                                },
                                {
                                    "name": "Sandstone",
                                    "description": "A touch of warmth",
                                    "thumbnail": "https://bootswatch.com/3/sandstone/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/sandstone/",
                                    "css": "https://bootswatch.com/3/sandstone/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/sandstone/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/sandstone/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/sandstone/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/sandstone/variables.less",
                                    "scss": "https://bootswatch.com/3/sandstone/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/sandstone/_variables.scss"
                                },
                                {
                                    "name": "Simplex",
                                    "description": "Mini and minimalist",
                                    "thumbnail": "https://bootswatch.com/3/simplex/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/simplex/",
                                    "css": "https://bootswatch.com/3/simplex/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/simplex/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/simplex/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/simplex/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/simplex/variables.less",
                                    "scss": "https://bootswatch.com/3/simplex/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/simplex/_variables.scss"
                                },
                                {
                                    "name": "Slate",
                                    "description": "Shades of gunmetal gray",
                                    "thumbnail": "https://bootswatch.com/3/slate/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/slate/",
                                    "css": "https://bootswatch.com/3/slate/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/slate/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/slate/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/slate/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/slate/variables.less",
                                    "scss": "https://bootswatch.com/3/slate/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/slate/_variables.scss"
                                },
                                {
                                    "name": "Spacelab",
                                    "description": "Silvery and sleek",
                                    "thumbnail": "https://bootswatch.com/3/spacelab/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/spacelab/",
                                    "css": "https://bootswatch.com/3/spacelab/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/spacelab/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/spacelab/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/spacelab/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/spacelab/variables.less",
                                    "scss": "https://bootswatch.com/3/spacelab/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/spacelab/_variables.scss"
                                },
                                {
                                    "name": "Superhero",
                                    "description": "The brave and the blue",
                                    "thumbnail": "https://bootswatch.com/3/superhero/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/superhero/",
                                    "css": "https://bootswatch.com/3/superhero/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/superhero/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/superhero/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/superhero/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/superhero/variables.less",
                                    "scss": "https://bootswatch.com/3/superhero/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/superhero/_variables.scss"
                                },
                                {
                                    "name": "United",
                                    "description": "Ubuntu orange and unique font",
                                    "thumbnail": "https://bootswatch.com/3/united/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/united/",
                                    "css": "https://bootswatch.com/3/united/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/united/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/united/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/united/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/united/variables.less",
                                    "scss": "https://bootswatch.com/3/united/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/united/_variables.scss"
                                },
                                {
                                    "name": "Yeti",
                                    "description": "A friendly foundation",
                                    "thumbnail": "https://bootswatch.com/3/yeti/thumbnail.png",
                                    "preview": "https://bootswatch.com/3/yeti/",
                                    "css": "https://bootswatch.com/3/yeti/bootstrap.css",
                                    "cssMin": "https://bootswatch.com/3/yeti/bootstrap.min.css",
                                    "cssCdn": "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/yeti/bootstrap.min.css",
                                    "less": "https://bootswatch.com/3/yeti/bootswatch.less",
                                    "lessVariables": "https://bootswatch.com/3/yeti/variables.less",
                                    "scss": "https://bootswatch.com/3/yeti/_bootswatch.scss",
                                    "scssVariables": "https://bootswatch.com/3/yeti/_variables.scss"
                                }
                            ]
                        }['themes']
                    ex_themes.extend([
                        {'name': t['name'], 'description': t['description'],
                            'css': t['cssMin'], 'thumbnail': t['thumbnail']}
                        for t in watch_themes])
                except Exception as e:
                    print(e)

                cache.set(THEME_CACHE_KEY, json.dumps(ex_themes), 24 * 3600)
                themes.extend(ex_themes)

        nodes.append(loader.render_to_string('xadmin/blocks/comm.top.theme.html', {'themes': themes, 'select_css': select_css}))
Exemplo n.º 34
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    before_filter_length = len(item['menus'])
                    item['menus'] = [
                        filter_item(i) for i in item['menus']
                        if check_menu_permission(i)
                    ]
                    after_filter_length = len(item['menus'])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = filter(lambda x: x, nav_menu)

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(nav_menu)
                self.request.session.modified = True

        def check_selected(menu, request):
            path = request.path
            selected = False
            if 'url' in menu:
                if menu.get("exact_match", False):
                    chop_index = -1
                    path = request.get_full_path()
                else:
                    chop_index = menu['url'].find('?')

                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, request)
                    if _s:
                        selected = True

            if selected:
                menu['selected'] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title or _(u'Django Xadmin'),
            'site_footer': self.site_footer or _(u'my-company.inc'),
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 35
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and "nav_menu" in self.request.session:
            nav_menu = json.loads(self.request.session["nav_menu"])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop("perm", None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == "super":
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if "menus" in item:
                    before_filter_length = len(item["menus"])
                    item["menus"] = [
                        filter_item(i) for i in item["menus"]
                        if check_menu_permission(i)
                    ]
                    after_filter_length = len(item["menus"])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = list(filter(lambda x: x, nav_menu))

            if not settings.DEBUG:
                self.request.session["nav_menu"] = json.dumps(
                    nav_menu, cls=JSONEncoder, ensure_ascii=False)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if "url" in menu:
                chop_index = menu["url"].find("?")
                if chop_index == -1:
                    selected = path.startswith(menu["url"])
                else:
                    selected = path.startswith(menu["url"][:chop_index])
            if "menus" in menu:
                for m in menu["menus"]:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu["selected"] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request.path)

        context.update({
            "menu_template": self.menu_template,
            "nav_menu": nav_menu,
            "site_title": self.site_title,
            "site_footer": self.site_footer,
            "breadcrumbs": self.get_breadcrumb(),
        })

        return context
Exemplo n.º 36
0
 def set_json(self, obj):
     self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)
Exemplo n.º 37
0
    def get_context(self):
        context = super(CommAdminView, self).get_context()

        if not settings.DEBUG and 'nav_menu' in self.request.session:
            nav_menu = json.loads(self.request.session['nav_menu'])
        else:
            menus = copy.copy(self.get_nav_menu())

            def check_menu_permission(item):
                need_perm = item.pop('perm', None)
                if need_perm is None:
                    return True
                elif callable(need_perm):
                    return need_perm(self.user)
                elif need_perm == 'super':
                    return self.user.is_superuser
                else:
                    return self.user.has_perm(need_perm)

            def filter_item(item):
                if 'menus' in item:
                    before_filter_length = len(item['menus'])
                    item['menus'] = [
                        filter_item(i) for i in item['menus']
                        if check_menu_permission(i)
                    ]
                    after_filter_length = len(item['menus'])
                    if after_filter_length == 0 and before_filter_length > 0:
                        return None
                return item

            nav_menu = [
                filter_item(item) for item in menus
                if check_menu_permission(item)
            ]
            nav_menu = list(filter(lambda x: x, nav_menu))

            if not settings.DEBUG:
                self.request.session['nav_menu'] = json.dumps(
                    nav_menu, cls=JSONEncoder, ensure_ascii=False)
                self.request.session.modified = True

        def check_selected(menu, path):
            selected = False
            if 'url' in menu:
                chop_index = menu['url'].find('?')
                if chop_index == -1:
                    selected = path.startswith(menu['url'])
                else:
                    selected = path.startswith(menu['url'][:chop_index])
            if 'menus' in menu:
                for m in menu['menus']:
                    _s = check_selected(m, path)
                    if _s:
                        selected = True
            if selected:
                menu['selected'] = True
            return selected

        for menu in nav_menu:
            check_selected(menu, self.request.path)

        # 添加自定义url,视图函数获取数据
        add_url_flag = False
        auto_title = ''
        pid = ''
        subtitle = ''
        print(self.request.get_full_path())
        if '/xadmin/cashflows/cash_title_content/' in self.request.get_full_path(
        ):
            from apps.cashflows.models import cash_title_link, cash_title_content
            add_url_flag = True
            auto_title = cash_title_link.objects.all()
            # print('title', title)
            pid = self.request.GET.get('pid')
            # print('pid', pid, type(pid))
            if pid:
                subtitle = cash_title_content.objects.filter(
                    content_cash_id=pid)
                pid = int(pid)
            else:
                subtitle = None
        else:
            pass

        print('auto_title', auto_title)
        print('pid', pid)
        print('subtitle', subtitle)

        context.update({
            'menu_template': self.menu_template,
            'nav_menu': nav_menu,
            'site_title': self.site_title,
            'site_footer': self.site_footer,
            'breadcrumbs': self.get_breadcrumb()
        })

        return context
Exemplo n.º 38
0
 def render_json(self, content):
     response = HttpResponse(mimetype="application/json; charset=UTF-8")
     response.write(
         json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
     return response
Exemplo n.º 39
0
    def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart["x-field"]
        y_fields = self.chart["y-field"]
        self.y_fields = (y_fields, ) if type(y_fields) not in (
            list, tuple) else y_fields

        datas = [{
            "data": [],
            "label":
            force_text(label_for_field(i, self.model, model_admin=self)),
        } for i in self.y_fields]

        self.make_result_list()

        for obj in self.result_list:
            xf, attrs, value = lookup_field(self.x_field, obj, self)
            for i, yfname in enumerate(self.y_fields):
                yf, yattrs, yv = lookup_field(yfname, obj, self)
                datas[i]["data"].append((value, yv))

        option = {
            "series": {
                "lines": {
                    "show": True
                },
                "points": {
                    "show": False
                }
            },
            "grid": {
                "hoverable": True,
                "clickable": True
            },
        }
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (
                    models.DateTimeField,
                    models.DateField,
                    models.TimeField,
            ):
                option["xaxis"] = {"mode": "time", "tickLength": 5}
                if type(xfield) is models.DateField:
                    option["xaxis"]["timeformat"] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option["xaxis"]["timeformat"] = "%H:%M:%S"
                else:
                    option["xaxis"]["timeformat"] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get("option", {}))

        content = {"data": datas, "option": option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)

        return HttpResponse(result)
Exemplo n.º 40
0
 def get_json_export(self, context):
     results = self._get_objects(context)
     return json.dumps({'objects': results}, ensure_ascii=False,
                       indent=(self.request.GET.get('export_json_format', 'off') == 'on') and 4 or None)
Exemplo n.º 41
0
 def set_json(self, obj):
     self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)