├── demoproject ├── __init__.py ├── .gitignore ├── demoproject │ ├── __init__.py │ ├── templates │ │ ├── home.html │ │ └── admin │ │ │ └── base_site.html │ ├── views.py │ ├── fixtures │ │ ├── auth_user.json │ │ └── test_data.json │ ├── urls.py │ ├── wsgi.py │ └── settings.py ├── .coveralls.yml ├── requirements.txt ├── manage.py ├── test_settings.py ├── menu.py └── dashboard.py ├── TODO ├── .coveralls.yml ├── admin_tools_stats ├── migrations │ ├── __init__.py │ ├── 0002_auto_20190920_1058.py │ └── 0001_initial.py ├── south_migrations │ ├── __init__.py │ ├── 0002_add_sum_field_name.py │ ├── 0003_add_operation_field_name.py │ └── 0001_initial_migration.py ├── fixtures │ ├── 10_dashboardstatscriteria_status.json │ ├── 20_dashboardstatscriteria_call_type.json │ └── initial_data.json ├── __init__.py ├── admin.py ├── templates │ └── admin_tools_stats │ │ └── modules │ │ └── chart.html ├── utils.py ├── app_label_renamer.py ├── tests.py ├── models.py └── modules.py ├── .coveragerc ├── docs ├── source │ ├── _static │ │ ├── admin_dashboard.png │ │ └── images │ │ │ └── admin_screenshot.png │ ├── introduction.rst │ ├── developer-doc │ │ ├── pre-requisite.rst │ │ ├── testing.rst │ │ ├── modules.rst │ │ └── objects-description.rst │ ├── developer-doc.rst │ ├── index.rst │ ├── installation-overview.rst │ ├── includes │ │ └── introduction.txt │ └── conf.py └── Makefile ├── MANIFEST.in ├── requirements.txt ├── CONTRIBUTORS ├── .gitignore ├── update_version.sh ├── MIT-LICENSE.txt ├── .travis.yml ├── setup.py ├── CHANGELOG.rst └── README.rst /demoproject/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | 2 | TODO 3 | ==== 4 | 5 | -------------------------------------------------------------------------------- /demoproject/.gitignore: -------------------------------------------------------------------------------- 1 | components 2 | -------------------------------------------------------------------------------- /demoproject/demoproject/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-pro 2 | -------------------------------------------------------------------------------- /admin_tools_stats/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /admin_tools_stats/south_migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /demoproject/.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-pro 2 | -------------------------------------------------------------------------------- /demoproject/requirements.txt: -------------------------------------------------------------------------------- 1 | django-nvd3 2 | django-bower -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | include = admin_tools_stats* 3 | plugins = 4 | django_coverage_plugin 5 | branch = True 6 | -------------------------------------------------------------------------------- /docs/source/_static/admin_dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/areski/django-admin-tools-stats/HEAD/docs/source/_static/admin_dashboard.png -------------------------------------------------------------------------------- /docs/source/introduction.rst: -------------------------------------------------------------------------------- 1 | .. _intro: 2 | 3 | ============ 4 | Introduction 5 | ============ 6 | 7 | .. include:: ./includes/introduction.txt 8 | -------------------------------------------------------------------------------- /demoproject/demoproject/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | Demo Project 3 | 4 | 5 | 6 |

Demo Project

7 | 8 | -------------------------------------------------------------------------------- /docs/source/_static/images/admin_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/areski/django-admin-tools-stats/HEAD/docs/source/_static/images/admin_screenshot.png -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | global-exclude *.pyc 2 | 3 | include README.rst 4 | include MIT-LICENSE.txt 5 | include requirements.txt 6 | 7 | recursive-include admin_tools_stats * 8 | recursive-include docs * 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-dateutil>=2.0 2 | django-jsonfield>=0.9.2 3 | django-qsstats-magic>=0.7.2 4 | djcacheutils>=3.0.0 5 | django-admin-tools>=0.5.1 6 | django-nvd3>=0.5.0 7 | django-bower 8 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | areski (Areski Belaid) 2 | shrenik (Shrenik Patel) 3 | engrost (Grzegorz Borys) 4 | andybak (Andy Baker) 5 | abarax (Leigh Appel) 6 | gannetson (Loek van Gent) 7 | hbkfabio (Fabio Duran Verdugo) 8 | PetrDlouhy (Petr Dlouhý) 9 | avaneesh23 (Avaneesh Murthy) 10 | -------------------------------------------------------------------------------- /docs/source/developer-doc/pre-requisite.rst: -------------------------------------------------------------------------------- 1 | .. _prerequisites: 2 | 3 | Prerequisites 4 | ============= 5 | 6 | To fully understand this project, developers will need to have an advanced knowledge of: 7 | - Django : http://www.djangoproject.com/ 8 | - Python : http://www.python.org/ 9 | -------------------------------------------------------------------------------- /demoproject/demoproject/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.shortcuts import render_to_response 3 | #from django.template.context import RequestContext 4 | 5 | 6 | def home(request): 7 | """ 8 | home page 9 | """ 10 | return render_to_response('home.html') 11 | -------------------------------------------------------------------------------- /demoproject/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /docs/source/developer-doc.rst: -------------------------------------------------------------------------------- 1 | .. _developer-doc: 2 | 3 | ======================= 4 | Developer Documentation 5 | ======================= 6 | 7 | Contents: 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | ./developer-doc/pre-requisite.rst 13 | ./developer-doc/objects-description.rst 14 | ./developer-doc/modules.rst 15 | ./developer-doc/testing.rst 16 | 17 | -------------------------------------------------------------------------------- /demoproject/test_settings.py: -------------------------------------------------------------------------------- 1 | from .demoproject.settings import * 2 | 3 | ROOT_URLCONF = 'demoproject.demoproject.urls' 4 | ADMIN_TOOLS_MENU = 'demoproject.menu.CustomMenu' 5 | ADMIN_TOOLS_INDEX_DASHBOARD = 'demoproject.dashboard.CustomIndexDashboard' 6 | ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'demoproject.dashboard.CustomAppIndexDashboard' 7 | 8 | FIXTURE_DIRS = ( 9 | 'demoproject/demoproject/fixtures/', 10 | ) 11 | -------------------------------------------------------------------------------- /admin_tools_stats/fixtures/10_dashboardstatscriteria_status.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk":1, 4 | "model":"admin_tools_stats.dashboardstatscriteria", 5 | "fields":{ 6 | "criteria_fix_mapping":{ 7 | "is_active":"1" 8 | }, 9 | "updated_date":"2011-09-01 09:06:12", 10 | "criteria_name":"status", 11 | "criteria_dynamic_mapping":{ 12 | 13 | }, 14 | "created_date":"2011-09-01 09:01:40" 15 | } 16 | } 17 | ] 18 | -------------------------------------------------------------------------------- /demoproject/demoproject/fixtures/auth_user.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fields": { 4 | "username": "admin", 5 | "first_name": "Admin", 6 | "is_superuser": true, 7 | "is_staff": true, 8 | "password": "pbkdf2_sha256$30000$uiktNFsHv8O2$yzKkLCtNRm674WYyV80LxjjXFJktDLPmKqXxrT0VfhE=", 9 | "last_name": "Admin", 10 | "email": "admin@email.com" 11 | }, 12 | "model": "auth.user", 13 | "pk": 1 14 | } 15 | ] 16 | 17 | -------------------------------------------------------------------------------- /demoproject/demoproject/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url, include 2 | 3 | # Uncomment the next two lines to enable the admin: 4 | from django.contrib import admin 5 | from .views import home 6 | admin.autodiscover() 7 | 8 | urlpatterns = [ 9 | url(r'^$', home, name='home'), 10 | 11 | # url(r'^demoproject/', include('demoproject.foo.urls')), 12 | 13 | # Uncomment the admin/doc line below to enable admin documentation: 14 | # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), 15 | 16 | url(r'^admin_tools/', include('admin_tools.urls')), 17 | url(r'^admin/', admin.site.urls), 18 | ] 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | demoproject/static 37 | 38 | *.db 39 | *nbproject* 40 | *devserver* 41 | *.idea* 42 | docs/build/* 43 | build/ 44 | dist/ 45 | *.egg-info/* 46 | *sublime* 47 | *~ 48 | -------------------------------------------------------------------------------- /update_version.sh: -------------------------------------------------------------------------------- 1 | # 2 | # Usage: 3 | # ./update_version.sh 0.9.0 4 | # 5 | 6 | git flow release start v$1 7 | sed -i -e "s/__version__ = '.*'/__version__ = '$1'/g" admin_tools_stats/__init__.py 8 | sed -i -e "s/version = '.*'/version = '$1'/g" docs/source/conf.py 9 | #rm -rf docs/html 10 | #python setup.py develop 11 | #make docs 12 | #git commit docs admin_tools_stats/__init__.py -m "Update to version v$1" 13 | git commit -a -m "Update to version v$1" 14 | git flow release finish v$1 15 | # python setup.py sdist upload -r pypi 16 | python setup.py sdist 17 | twine upload dist/django-admin-tools-stats-$1.tar.gz 18 | git push origin develop; git push origin master; git push --tags 19 | -------------------------------------------------------------------------------- /admin_tools_stats/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # 5 | # This Source Code Form is subject to the terms of the Mozilla Public 6 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 7 | # You can obtain one at http://mozilla.org/MPL/2.0/. 8 | # 9 | # Copyright (C) 2011-2014 Star2Billing S.L. 10 | # 11 | # The Initial Developer of the Original Code is 12 | # Arezqui Belaid 13 | # 14 | 15 | 16 | __version__ = '0.9.0' # edit also docs/source/conf.py and update requirements.txt 17 | __author__ = "Arezqui Belaid" 18 | __contact__ = "areski@gmail.com" 19 | __homepage__ = "http://www.areskibelaid.com" 20 | __docformat__ = "restructuredtext" 21 | -------------------------------------------------------------------------------- /docs/source/developer-doc/testing.rst: -------------------------------------------------------------------------------- 1 | .. _testing: 2 | 3 | Test Case Descriptions 4 | ====================== 5 | 6 | ---------------- 7 | How to run tests 8 | ---------------- 9 | 10 | **1. Run full test suite**:: 11 | 12 | $ python manage.py test --verbosity=2 13 | 14 | **2. Run AdminToolsStatsAdminInterfaceTestCase**:: 15 | 16 | $ python manage.py test admin_tools_stats.AdminToolsStatsAdminInterfaceTestCase --verbosity=2 17 | 18 | 19 | --------- 20 | Test Case 21 | --------- 22 | 23 | .. _AdminToolsStatsAdminInterfaceTestCase-model: 24 | 25 | :class:`AdminToolsStatsAdminInterfaceTestCase` 26 | ---------------------------------------------- 27 | 28 | Test cases for django-admin-tools-stats Admin Interface. 29 | -------------------------------------------------------------------------------- /docs/source/developer-doc/modules.rst: -------------------------------------------------------------------------------- 1 | .. _modules: 2 | 3 | Django-admin-tools-stats Modules 4 | ================================ 5 | 6 | .. _DashboardChart: 7 | 8 | :class:`DashboardChart` 9 | ----------------------- 10 | 11 | Dashboard module with user registration charts. Default values are best suited 12 | for 2-column dashboard layouts. 13 | 14 | def **get_registrations(self, interval, days, graph_key, select_box_value):** 15 | Returns an array with new users count per interval. 16 | 17 | def **prepare_template_data(self, data, graph_key, select_box_value):** 18 | Prepares data for template (passed as module attributes) 19 | 20 | 21 | .. _DashboardCharts: 22 | 23 | :class:`DashboardCharts` 24 | ------------------------ 25 | 26 | Group module with 3 default dashboard charts 27 | -------------------------------------------------------------------------------- /admin_tools_stats/fixtures/20_dashboardstatscriteria_call_type.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk":2, 4 | "model":"admin_tools_stats.dashboardstatscriteria", 5 | "fields":{ 6 | "criteria_fix_mapping":null, 7 | "updated_date":"2011-09-02 05:51:41", 8 | "criteria_name":"call_type", 9 | "dynamic_criteria_field_name":"disposition", 10 | "criteria_dynamic_mapping":{ 11 | "INVALIDARGS":"INVALIDARGS", 12 | "BUSY":"BUSY", 13 | "TORTURE":"TORTURE", 14 | "ANSWER":"ANSWER", 15 | "DONTCALL":"DONTCALL", 16 | "FORBIDDEN":"FORBIDDEN", 17 | "NOROUTE":"NOROUTE", 18 | "CHANUNAVAIL":"CHANUNAVAIL", 19 | "NOANSWER":"NOANSWER", 20 | "CONGESTION":"CONGESTION", 21 | "CANCEL":"CANCEL" 22 | }, 23 | "created_date":"2011-09-02 05:51:41" 24 | } 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. Django-admin-tools-stats documentation master file, created by 2 | sphinx-quickstart on Mon Apr 25 23:21:38 2011. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | 7 | Django Admin Tools Stats Documentation! 8 | ========================== 9 | 10 | :Release: |version| 11 | :Date: |today| 12 | :Keywords: django, python, plot, graph, nvd3, d3, dashboard 13 | :Author: Arezqui Belaid 14 | :Description: Django-admin-tools-stats is a Django admin module that allow you to create easily charts on your dashboard based on specific models and criterias. 15 | 16 | 17 | Contents: 18 | 19 | .. toctree:: 20 | :maxdepth: 2 21 | 22 | introduction 23 | installation-overview 24 | developer-doc 25 | 26 | 27 | Indices and tables 28 | ================== 29 | 30 | * :ref:`genindex` 31 | * :ref:`modindex` 32 | * :ref:`search` 33 | -------------------------------------------------------------------------------- /admin_tools_stats/fixtures/initial_data.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk":1, 4 | "model":"admin_tools_stats.dashboardstatscriteria", 5 | "fields":{ 6 | "criteria_fix_mapping":{ 7 | "is_active":"1" 8 | }, 9 | "updated_date":"2011-09-01 09:06:12", 10 | "criteria_name":"status", 11 | "dynamic_criteria_field_name":"", 12 | "criteria_dynamic_mapping":{ 13 | 14 | }, 15 | "created_date":"2011-09-01 09:01:40" 16 | } 17 | }, 18 | { 19 | "pk":1, 20 | "model":"admin_tools_stats.dashboardstats", 21 | "fields":{ 22 | "updated_date":"2011-09-01 09:11:56", 23 | "is_visible":true, 24 | "graph_key":"user_graph", 25 | "graph_title":"User graph", 26 | "criteria":[ 27 | 1 28 | ], 29 | "date_field_name":"date_joined", 30 | "operation_field_name":"", 31 | "type_operation_field_name":"", 32 | "model_name":"User", 33 | "created_date":"2011-09-01 08:56:45", 34 | "model_app_name":"auth" 35 | } 36 | } 37 | ] 38 | -------------------------------------------------------------------------------- /MIT-LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | django-admin-tools-stats 4 | 5 | Copyright (c) 2011-2015 Arezqui Belaid and other contributors 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the 9 | "Software"), to deal in the Software without restriction, including 10 | without limitation the rights to use, copy, modify, merge, publish, 11 | distribute, sublicense, and/or sell copies of the Software, and to 12 | permit persons to whom the Software is furnished to do so, subject to 13 | the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be 16 | included in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 19 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 20 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 21 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 22 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 24 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 25 | -------------------------------------------------------------------------------- /demoproject/menu.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file was generated with the custommenu management command, it contains 3 | the classes for the admin menu, you can customize this class as you want. 4 | 5 | To activate your custom menu add the following to your settings.py:: 6 | ADMIN_TOOLS_MENU = 'demoproject.menu.CustomMenu' 7 | """ 8 | 9 | try: 10 | from django.urls import reverse 11 | except ImportError: # Django<2.0 12 | from django.core.urlresolvers import reverse 13 | from django.utils.translation import ugettext_lazy as _ 14 | 15 | from admin_tools.menu import items, Menu 16 | 17 | 18 | class CustomMenu(Menu): 19 | """ 20 | Custom Menu for demoproject admin site. 21 | """ 22 | def __init__(self, **kwargs): 23 | Menu.__init__(self, **kwargs) 24 | self.children += [ 25 | items.MenuItem(_('Dashboard'), reverse('admin:index')), 26 | items.Bookmarks(), 27 | items.AppList( 28 | _('Applications'), 29 | exclude=('django.contrib.*',) 30 | ), 31 | items.AppList( 32 | _('Administration'), 33 | models=('django.contrib.*',) 34 | ) 35 | ] 36 | 37 | def init_with_context(self, context): 38 | """ 39 | Use this method if you need to access the request context. 40 | """ 41 | return super(CustomMenu, self).init_with_context(context) 42 | -------------------------------------------------------------------------------- /docs/source/developer-doc/objects-description.rst: -------------------------------------------------------------------------------- 1 | .. _objects-description: 2 | 3 | Objects Description 4 | =================== 5 | 6 | .. _DashboardStatsCriteria-model: 7 | 8 | :class:`DashboardStatsCriteria` 9 | ------------------------------- 10 | 11 | To configure criteria for dashboard graphs 12 | 13 | **Attributes**: 14 | 15 | * ``criteria_name`` - Unique word . 16 | * ``criteria_fix_mapping`` - JSON data key-value pairs. 17 | * ``dynamic_criteria_field_name`` - Dynamic criteria field. 18 | * ``criteria_dynamic_mapping`` - JSON data key-value pairs. 19 | * ``created_date`` - record created date. 20 | * ``updated_date`` - record updated date. 21 | 22 | **Name of DB table**: dash_stats_criteria 23 | 24 | 25 | .. _DashboardStats-model: 26 | 27 | :class:`DashboardStats` 28 | ----------------------- 29 | 30 | To configure graphs for dashboard 31 | 32 | **Attributes**: 33 | 34 | * ``graph_key`` - unique graph name. 35 | * ``graph_title`` - graph title. 36 | * ``model_app_name`` - App name of model. 37 | * ``model_name`` - model name. 38 | * ``date_field_name`` - Date field of model_name. 39 | * ``criteria`` - many-to-many relationship. 40 | * ``is_visible`` - enable/disable. 41 | * ``created_date`` - record created date. 42 | * ``updated_date`` - record updated date. 43 | 44 | **Name of DB table**: dashboard_stats 45 | -------------------------------------------------------------------------------- /demoproject/demoproject/templates/admin/base_site.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/base.html" %} 2 | {% load i18n admin_tools_menu_tags static %} 3 | 4 | {% block title %}{% trans 'Admin' %}{% endblock %} 5 | {% block extrahead %} 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 23 | {% endblock %} 24 | 25 | {% block extrastyle %} 26 | {{ block.super }} 27 | {% if user.is_active and user.is_staff %} 28 | {% if not is_popup %} 29 | {% admin_tools_render_menu_css %} 30 | {% endif %} 31 | {% endif %} 32 | {% endblock %} 33 | 34 | 35 | {% block nav-global %} 36 | {% if user.is_active and user.is_staff %} 37 | {% if not is_popup %} 38 | {% admin_tools_render_menu %} 39 | {% endif %} 40 | {% endif %} 41 | {% endblock %} 42 | -------------------------------------------------------------------------------- /demoproject/demoproject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for demoproject project. 3 | 4 | This module contains the WSGI application used by Django's development server 5 | and any production WSGI deployments. It should expose a module-level variable 6 | named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover 7 | this application via the ``WSGI_APPLICATION`` setting. 8 | 9 | Usually you will have the standard Django WSGI application here, but it also 10 | might make sense to replace the whole Django WSGI application with a custom one 11 | that later delegates to the Django one. For example, you could introduce WSGI 12 | middleware here, or combine a Django application with an application of another 13 | framework. 14 | 15 | """ 16 | import os 17 | 18 | # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks 19 | # if running multiple sites in the same mod_wsgi process. To fix this, use 20 | # mod_wsgi daemon mode with each site in its own daemon process, or use 21 | # os.environ["DJANGO_SETTINGS_MODULE"] = "demoproject.settings" 22 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings") 23 | 24 | # This application object is used by any WSGI server configured to use this 25 | # file. This includes Django's development server, if the WSGI_APPLICATION 26 | # setting points here. 27 | from django.core.wsgi import get_wsgi_application 28 | application = get_wsgi_application() 29 | 30 | # Apply WSGI middleware here. 31 | # from helloworld.wsgi import HelloWorldApplication 32 | # application = HelloWorldApplication(application) 33 | -------------------------------------------------------------------------------- /admin_tools_stats/admin.py: -------------------------------------------------------------------------------- 1 | # 2 | # This Source Code Form is subject to the terms of the Mozilla Public 3 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | # You can obtain one at http://mozilla.org/MPL/2.0/. 5 | # 6 | # Copyright (C) 2011-2014 Star2Billing S.L. 7 | # 8 | # The Initial Developer of the Original Code is 9 | # Arezqui Belaid 10 | # 11 | from django.contrib import admin 12 | from django.utils.translation import ugettext_lazy as _ 13 | from admin_tools_stats.models import DashboardStatsCriteria, DashboardStats 14 | from admin_tools_stats.app_label_renamer import AppLabelRenamer 15 | AppLabelRenamer(native_app_label=u'admin_tools_stats', app_label=_('Admin Tools Stats')).main() 16 | 17 | 18 | class DashboardStatsCriteriaAdmin(admin.ModelAdmin): 19 | """ 20 | Allows the administrator to view and modify certain attributes 21 | of a DashboardStats. 22 | """ 23 | list_display = ('id', 'criteria_name', 'created_date') 24 | list_filter = ['created_date'] 25 | ordering = ('id', ) 26 | save_as = True 27 | 28 | admin.site.register(DashboardStatsCriteria, DashboardStatsCriteriaAdmin) 29 | 30 | 31 | class DashboardStatsAdmin(admin.ModelAdmin): 32 | """ 33 | Allows the administrator to view and modify certain attributes 34 | of a DashboardStats. 35 | """ 36 | list_display = ('id', 'graph_key', 'graph_title', 'model_name', 37 | 'is_visible', 'created_date') 38 | list_filter = ['created_date'] 39 | ordering = ('id', ) 40 | save_as = True 41 | 42 | admin.site.register(DashboardStats, DashboardStatsAdmin) 43 | -------------------------------------------------------------------------------- /demoproject/demoproject/fixtures/test_data.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk":1, 4 | "model":"admin_tools_stats.dashboardstatscriteria", 5 | "fields":{ 6 | "criteria_fix_mapping":{ 7 | "is_active":"1" 8 | }, 9 | "updated_date":"2011-09-01 09:06:12", 10 | "criteria_name":"active", 11 | "dynamic_criteria_field_name":"", 12 | "criteria_dynamic_mapping":{ 13 | "true": "Active", 14 | "false": "Inactive" 15 | }, 16 | "created_date":"2011-09-01 09:01:40" 17 | } 18 | }, 19 | { 20 | "pk":2, 21 | "model":"admin_tools_stats.dashboardstats", 22 | "fields":{ 23 | "updated_date":"2011-09-01 09:11:56", 24 | "is_visible":true, 25 | "graph_key":"user_logged_graph", 26 | "graph_title":"User logged in graph", 27 | "criteria":[ 28 | 1 29 | ], 30 | "date_field_name":"last_login", 31 | "operation_field_name":"is_staff", 32 | "type_operation_field_name":"Sum", 33 | "model_name":"User", 34 | "created_date":"2011-09-01 08:56:45", 35 | "model_app_name":"auth" 36 | } 37 | }, 38 | { 39 | "pk":1, 40 | "model":"admin_tools_stats.dashboardstats", 41 | "fields":{ 42 | "updated_date":"2011-09-01 09:11:56", 43 | "is_visible":true, 44 | "graph_key":"user_graph", 45 | "graph_title":"User graph", 46 | "criteria":[ 47 | 1 48 | ], 49 | "date_field_name":"date_joined", 50 | "operation_field_name":"", 51 | "type_operation_field_name":"", 52 | "model_name":"User", 53 | "created_date":"2011-09-01 08:56:45", 54 | "model_app_name":"auth" 55 | } 56 | } 57 | ] 58 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: python 4 | 5 | python: 6 | - "2.7" 7 | - "3.4" 8 | - "3.5" 9 | - "3.6" 10 | - "3.7" 11 | 12 | env: 13 | matrix: 14 | - DJANGO_VERSION="Django>=1.11,<2.0" 15 | - DJANGO_VERSION="Django>=2.0,<2.1" 16 | - DJANGO_VERSION="Django>=2.1,<2.2" 17 | - DJANGO_VERSION="Django>=2.2,<3.0" 18 | - DJANGO_VERSION="--pre Django>=3.0,<3.1" 19 | - DJANGO_VERSION='https://github.com/django/django/archive/master.tar.gz' 20 | 21 | cache: 22 | directories: 23 | - $HOME/.cache/pip 24 | 25 | install: 26 | - pip install 'coverage<4' # coverage>=4 has issues with python3 27 | - pip install -q $DJANGO_VERSION 28 | - pip install -q coveralls 29 | - pip install -r requirements.txt 30 | 31 | matrix: 32 | exclude: 33 | - python: "2.7" 34 | env: DJANGO_VERSION="Django>=2.0,<2.1" 35 | - python: "2.7" 36 | env: DJANGO_VERSION="Django>=2.1,<2.2" 37 | - python: "2.7" 38 | env: DJANGO_VERSION="Django>=2.2,<3.0" 39 | - python: "2.7" 40 | env: DJANGO_VERSION="--pre Django>=3.0,<3.1" 41 | - python: "2.7" 42 | env: DJANGO_VERSION='https://github.com/django/django/archive/master.tar.gz' 43 | - python: "3.4" 44 | env: DJANGO_VERSION='https://github.com/django/django/archive/master.tar.gz' 45 | - python: "3.4" 46 | env: DJANGO_VERSION="--pre Django>=3.0,<3.1" 47 | - python: "3.4" 48 | env: DJANGO_VERSION="Django>=2.1,<2.2" 49 | - python: "3.4" 50 | env: DJANGO_VERSION="Django>=2.2,<3.0" 51 | - python: "3.5" 52 | env: DJANGO_VERSION="--pre Django>=3.0,<3.1" 53 | - python: "3.5" 54 | env: DJANGO_VERSION='https://github.com/django/django/archive/master.tar.gz' 55 | allow_failures: 56 | - env: DJANGO_VERSION="--pre Django>=3.0,<3.1" 57 | - env: DJANGO_VERSION='https://github.com/django/django/archive/master.tar.gz' 58 | 59 | before_cache: 60 | - rm -f $HOME/.cache/pip/log/debug.log 61 | 62 | script: 63 | - django-admin --version 64 | - python -Wall $VIRTUAL_ENV/bin/coverage run setup.py test 65 | 66 | after_success: 67 | - coveralls 68 | -------------------------------------------------------------------------------- /admin_tools_stats/migrations/0002_auto_20190920_1058.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2019-09-20 02:58 2 | 3 | from django.db import migrations, models 4 | import jsonfield.fields 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('admin_tools_stats', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AddField( 15 | model_name='dashboardstats', 16 | name='user_field_name', 17 | field=models.CharField(blank=True, help_text='ex. owner, invitation__owner', max_length=90, null=True, verbose_name='user field name'), 18 | ), 19 | migrations.AlterField( 20 | model_name='dashboardstats', 21 | name='date_field_name', 22 | field=models.CharField(help_text='ex. date_joined, invitation__invitation_date', max_length=90, verbose_name='date field name'), 23 | ), 24 | migrations.AlterField( 25 | model_name='dashboardstats', 26 | name='graph_key', 27 | field=models.CharField(help_text='it needs to be one word unique. ex. auth, mygraph', max_length=90, unique=True, verbose_name='graph identifier'), 28 | ), 29 | migrations.AlterField( 30 | model_name='dashboardstats', 31 | name='operation_field_name', 32 | field=models.CharField(blank=True, help_text='The field you want to aggregate, ex. amount, salaries__total_income', max_length=90, null=True, verbose_name='Operate field name'), 33 | ), 34 | migrations.AlterField( 35 | model_name='dashboardstats', 36 | name='type_operation_field_name', 37 | field=models.CharField(blank=True, choices=[('DistinctCount', 'DistinctCount'), ('Count', 'Count'), ('Sum', 'Sum'), ('Avg', 'Avg'), ('Max', 'Max'), ('Min', 'Min'), ('StdDev', 'StdDev'), ('Variance', 'Variance')], help_text='choose the type operation what you want to aggregate, ex. Sum', max_length=90, null=True, verbose_name='Choose Type operation'), 38 | ), 39 | migrations.AlterField( 40 | model_name='dashboardstatscriteria', 41 | name='criteria_dynamic_mapping', 42 | field=jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that will be used for the criteria Ex. "{\'false\': \'Inactive\', \'true\': \'Active\'}"', null=True, verbose_name='dynamic criteria / value'), 43 | ), 44 | ] 45 | -------------------------------------------------------------------------------- /admin_tools_stats/templates/admin_tools_stats/modules/chart.html: -------------------------------------------------------------------------------- 1 | {% extends "admin_tools/dashboard/module.html" %} 2 | {% load nvd3_tags %} 3 | 4 | {% if module.require_chart_jscss %} 5 | {% load static %} 6 | {% endif %} 7 | 8 | {% block module_content %} 9 | {# Jquery CDN : Needed when using jquery_on_ready=True #} 10 | {% if module.extra.jquery_on_ready %} 11 | 12 | {% endif %} 13 | {% if module.require_chart_jscss %} 14 | 15 | 16 | 17 | {% endif %} 18 | 19 | 52 | 53 | {% if module.form_field %} 54 |
{% csrf_token %} 55 | {{ module.form_field }} 56 |
57 |
58 | {% endif %} 59 | 60 | {% include_container module.chart_container module.chart_height module.chart_width %} 61 | 62 | {% endblock %} 63 | 64 | -------------------------------------------------------------------------------- /docs/source/installation-overview.rst: -------------------------------------------------------------------------------- 1 | .. _installation-overview: 2 | 3 | ===================== 4 | Installation overview 5 | ===================== 6 | 7 | .. _install-requirements: 8 | 9 | Install requirements 10 | ==================== 11 | 12 | To get started with Django-admin-tools-stats you must have the following installed: 13 | 14 | - Django Framework >= 1.4 (Python based Web framework) 15 | - python-dateutil >= 1.5 (Extensions to the standard datetime module) 16 | - django-admin-tools (Collection of tools for Django administration) 17 | - django-cache-utils (To provide utilities for making cache-related work easier) 18 | - django-jsonfield >= 0.6 (Reusable Django field that can use inside models) 19 | - django-nvd3 >= 0.5.0 (Django wrapper for nvd3 - It's time for beautiful charts) 20 | - python-memcached >= 1.47 (Python based API for communicating with the memcached 21 | distributed memory object cache daemon) 22 | 23 | 24 | Use PIP to install the dependencies listed in the requirments file,:: 25 | 26 | $ pip install -r requirements.txt 27 | 28 | 29 | .. _configuration: 30 | 31 | Configuration 32 | ============= 33 | 34 | - Configure django-admin-tools, refer to the documentation of http://django-admin-tools.readthedocs.org/en/latest/ 35 | 36 | - Add ``admin_tools_stats`` & ``django_nvd3`` into INSTALLED_APPS in settings.py:: 37 | 38 | INSTALLED_APPS = ( 39 | 'admin_tools_stats', 40 | 'django_nvd3', 41 | ) 42 | 43 | - Add the following code to your file dashboard.py:: 44 | 45 | from admin_tools_stats.modules import DashboardCharts, get_active_graph 46 | 47 | # append an app list module for "Country_prefix" 48 | self.children.append(modules.AppList( 49 | _('Dashboard Stats Settings'), 50 | models=('admin_tools_stats.*', ), 51 | )) 52 | 53 | # Copy following code into your custom dashboard 54 | # append following code after recent actions module or 55 | # a link list module for "quick links" 56 | graph_list = get_active_graph() 57 | for i in graph_list: 58 | kwargs = {} 59 | kwargs['graph_key'] = i.graph_key 60 | kwargs['require_chart_jscss'] = False 61 | 62 | for key in context['request'].POST: 63 | if key.startswith('select_box_'): 64 | kwargs[key] = context['request'].POST[key] 65 | 66 | self.children.append(DashboardCharts(**kwargs)) 67 | 68 | - To create the tables needed by Django-admin-tools-stats, run the following command:: 69 | 70 | $ python manage.py syncdb 71 | 72 | 73 | - Open admin panel, configure ``Dashboard Stats Criteria`` & ``Dashboard Stats`` respectively 74 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | import os 3 | import re 4 | import admin_tools_stats 5 | 6 | 7 | def runtests(): 8 | import os 9 | import sys 10 | 11 | import django 12 | from django.core.management import call_command 13 | 14 | os.environ['DJANGO_SETTINGS_MODULE'] = 'demoproject.test_settings' 15 | django.setup() 16 | call_command('test', 'admin_tools_stats') 17 | sys.exit() 18 | 19 | 20 | def read(*parts): 21 | return open(os.path.join(os.path.dirname(__file__), *parts)).read() 22 | 23 | 24 | def parse_requirements(file_name): 25 | requirements = [] 26 | for line in open(file_name, 'r').read().split('\n'): 27 | if re.match(r'(\s*#)|(\s*$)', line): 28 | continue 29 | if re.match(r'\s*-e\s+', line): 30 | requirements.append(re.sub(r'\s*-e\s+.*#egg=(.*)$', r'\1', line)) 31 | elif re.match(r'(\s*git)|(\s*hg)', line): 32 | pass 33 | else: 34 | requirements.append(line) 35 | return requirements 36 | 37 | 38 | def parse_dependency_links(file_name): 39 | dependency_links = [] 40 | for line in open(file_name, 'r').read().split('\n'): 41 | if re.match(r'\s*-[ef]\s+', line): 42 | dependency_links.append(re.sub(r'\s*-[ef]\s+', '', line)) 43 | 44 | return dependency_links 45 | 46 | 47 | setup( 48 | name='django-admin-tools-stats', 49 | version=admin_tools_stats.__version__, 50 | description='django-admin-tools-stats - Django-admin module to create charts and stats in your dashboard', 51 | long_description=read('README.rst'), 52 | author='Belaid Arezqui', 53 | author_email='areski@gmail.com', 54 | url='https://github.com/areski/django-admin-tools-stats', 55 | include_package_data=True, 56 | zip_safe=False, 57 | package_dir={'admin_tools_stats': 'admin_tools_stats'}, 58 | packages=find_packages(), 59 | package_data={}, 60 | install_requires=parse_requirements('requirements.txt'), 61 | dependency_links=parse_dependency_links('requirements.txt'), 62 | license='MIT License', 63 | classifiers=[ 64 | 'Development Status :: 5 - Production/Stable', 65 | 'Environment :: Web Environment', 66 | 'Framework :: Django', 67 | 'Intended Audience :: Developers', 68 | 'License :: OSI Approved :: MIT License', 69 | 'Operating System :: OS Independent', 70 | 'Programming Language :: Python', 71 | 'Programming Language :: Python :: 2', 72 | 'Programming Language :: Python :: 2.6', 73 | 'Programming Language :: Python :: 2.7', 74 | 'Programming Language :: Python :: 3', 75 | 'Programming Language :: Python :: 3.4', 76 | 'Programming Language :: Python :: 3.5', 77 | 'Topic :: Software Development :: Libraries :: Python Modules' 78 | ], 79 | extras_require={ 80 | ':python_version < "3.0"': ['Django>=1.8,<2.0'], 81 | ':python_version >= "3.0"': ['Django>=1.8'], 82 | }, 83 | test_suite='setup.runtests', 84 | ) 85 | -------------------------------------------------------------------------------- /admin_tools_stats/south_migrations/0002_add_sum_field_name.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from south.utils import datetime_utils as datetime 3 | from south.db import db 4 | from south.v2 import SchemaMigration 5 | from django.db import models 6 | 7 | 8 | class Migration(SchemaMigration): 9 | 10 | def forwards(self, orm): 11 | # Adding field 'DashboardStats.sum_field_name' 12 | db.add_column(u'dashboard_stats', 'sum_field_name', 13 | self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True), 14 | keep_default=False) 15 | 16 | 17 | def backwards(self, orm): 18 | # Deleting field 'DashboardStats.sum_field_name' 19 | db.delete_column(u'dashboard_stats', 'sum_field_name') 20 | 21 | 22 | models = { 23 | u'admin_tools_stats.dashboardstats': { 24 | 'Meta': {'object_name': 'DashboardStats', 'db_table': "u'dashboard_stats'"}, 25 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 26 | 'criteria': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['admin_tools_stats.DashboardStatsCriteria']", 'null': 'True', 'blank': 'True'}), 27 | 'date_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 28 | 'graph_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '90'}), 29 | 'graph_title': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 30 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 31 | 'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 32 | 'model_app_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 33 | 'model_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 34 | 'sum_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 35 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 36 | }, 37 | u'admin_tools_stats.dashboardstatscriteria': { 38 | 'Meta': {'object_name': 'DashboardStatsCriteria', 'db_table': "u'dash_stats_criteria'"}, 39 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 40 | 'criteria_dynamic_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 41 | 'criteria_fix_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 42 | 'criteria_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 43 | 'dynamic_criteria_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 44 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 45 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 46 | } 47 | } 48 | 49 | complete_apps = ['admin_tools_stats'] -------------------------------------------------------------------------------- /docs/source/includes/introduction.txt: -------------------------------------------------------------------------------- 1 | :Version: |version| 2 | :Date: |today| 3 | :Keywords: django, python, plot, graph, nvd3, d3, dashboard 4 | :Author: Arezqui Belaid 5 | :License: MIT 6 | 7 | -- 8 | 9 | .. _django-admin-tools-stats-synopsis: 10 | 11 | 12 | Django-admin-tools-stats is a Django admin module that allows you to easily create charts on your dashboard based on specific models and criterias. 13 | 14 | It will query your models and provide reporting and statistics graphs, simple to read and display on your Dashboard. 15 | 16 | Django-admin-tools-stats is an open source project written in Python and using the ``Django`` Framework. 17 | 18 | 19 | 20 | .. _overview: 21 | 22 | Overview 23 | ======== 24 | 25 | Django-admin-tools-stats is a Django application which powers dashboard modules with customer statistics and charts. 26 | 27 | The goal of this project is to quickly interrogate your model data to provide reports and statistics graphs which are simple to read and can be used on a Dashboard. 28 | 29 | 30 | .. image:: ./_static/admin_dashboard.png 31 | :width: 1000 32 | 33 | 34 | .. _installation: 35 | 36 | Installation 37 | ------------ 38 | 39 | Install, upgrade and uninstall django-nvd3.py with these commands:: 40 | 41 | $ sudo pip install django-admin-tools-stats 42 | $ sudo pip install --upgrade django-admin-tools-stats 43 | $ sudo pip uninstall django-admin-tools-stats 44 | 45 | Or if you don't have `pip`:: 46 | 47 | $ sudo easy_install django-admin-tools-stats 48 | 49 | 50 | .. _usage: 51 | 52 | Usage 53 | ----- 54 | 55 | These tools have been created to improve the django-admin-tools : http://django-admin-tools.readthedocs.org 56 | 57 | With Django-admin-tools you will be able to create and include charts on your dashboard and monitor your data, for instance you can easily monitor new users signing up each day, or new campaigns created per week. 58 | 59 | Django-admin-tools also allow you to display a button 'Select' that will behave as a filter on the model data. 60 | 61 | 62 | .. _contributing: 63 | 64 | Contributing 65 | ============ 66 | 67 | Development of django-admin-tools-stats takes place on Github: 68 | 69 | https://github.com/Star2Billing/django-admin-tools-stats 70 | 71 | Bug tracker: https://github.com/Star2Billing/django-admin-tools-stats/issues 72 | 73 | 74 | .. _source_download: 75 | 76 | Source download 77 | =============== 78 | 79 | The source code is currently available on github. Fork away! 80 | 81 | https://github.com/Star2Billing/django-admin-tools-stats 82 | 83 | Available also on PyPi : https://pypi.python.org/pypi/django-admin-tools-stats 84 | 85 | 86 | .. _documentation: 87 | 88 | Documentation 89 | ============= 90 | 91 | Find the project documentation : http://django-admin-user-stats.readthedocs.org 92 | 93 | 94 | .. _credits: 95 | 96 | Credits 97 | ======= 98 | 99 | Django-admin-tools-stats was inspired by django-admin-user-stats : 100 | https://github.com/kmike/django-admin-user-stats 101 | 102 | 103 | .. _license: 104 | 105 | License 106 | ======= 107 | 108 | Copyright (c) 2011-2014 Arezqui Belaid 109 | 110 | Django-nvd3 is licensed under MIT, see `MIT-LICENSE.txt`. 111 | -------------------------------------------------------------------------------- /admin_tools_stats/utils.py: -------------------------------------------------------------------------------- 1 | # 2 | # This Source Code Form is subject to the terms of the Mozilla Public 3 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | # You can obtain one at http://mozilla.org/MPL/2.0/. 5 | # 6 | # Copyright (C) 2011-2014 Star2Billing S.L. 7 | # 8 | # The Initial Developer of the Original Code is 9 | # Arezqui Belaid 10 | # 11 | 12 | from django.contrib.auth.models import User 13 | from django.test import TestCase, Client 14 | from django.test.client import RequestFactory 15 | import base64 16 | import unittest 17 | import inspect 18 | 19 | 20 | def build_test_suite_from(test_cases): 21 | """Returns a single or group of unittest test suite(s) that's ready to be 22 | run. The function expects a list of classes that are subclasses of 23 | TestCase. 24 | 25 | The function will search the module where each class resides and 26 | build a test suite from that class and all subclasses of it. 27 | """ 28 | test_suites = [] 29 | for test_case in test_cases: 30 | mod = __import__(test_case.__module__) 31 | components = test_case.__module__.split('.') 32 | for comp in components[1:]: 33 | mod = getattr(mod, comp) 34 | tests = [] 35 | for item in mod.__dict__.values(): 36 | if type(item) is type and issubclass(item, test_case): 37 | tests.append(item) 38 | test_suites.append(unittest.TestSuite( 39 | map(unittest.TestLoader().loadTestsFromTestCase, tests))) 40 | 41 | return unittest.TestSuite(test_suites) 42 | 43 | 44 | class BaseAuthenticatedClient(TestCase): 45 | """Common Authentication""" 46 | fixtures = ['auth_user'] 47 | 48 | def setUp(self): 49 | """To create admin user""" 50 | self.client = Client() 51 | self.user = User.objects.get(username='admin') 52 | auth = '%s:%s' % ('admin', 'admin') 53 | auth = 'Basic %s' % base64.encodestring(auth.encode('utf8')) 54 | auth = auth.strip() 55 | self.extra = { 56 | 'HTTP_AUTHORIZATION': auth, 57 | } 58 | try: 59 | self.client.force_login(self.user) 60 | except AttributeError: # Django < 1.8 61 | login = self.client.login(username='admin', password='admin') 62 | self.assertTrue(login) 63 | 64 | self.factory = RequestFactory() 65 | 66 | 67 | class Choice(object): 68 | 69 | class __metaclass__(type): 70 | def __init__(self, *args, **kwargs): 71 | self._data = [] 72 | for name, value in inspect.getmembers(self): 73 | if not name.startswith('_') and not inspect.ismethod(value): 74 | if isinstance(value, tuple) and len(value) > 1: 75 | data = value 76 | else: 77 | pieces = [x.capitalize() for x in name.split('_')] 78 | data = (value, ' '.join(pieces)) 79 | self._data.append(data) 80 | setattr(self, name, data[0]) 81 | 82 | self._hash = dict(self._data) 83 | 84 | def __iter__(self): 85 | for value, data in self._data: 86 | yield value, data 87 | 88 | @classmethod 89 | def get_value(self, key): 90 | return self._hash[key] 91 | -------------------------------------------------------------------------------- /admin_tools_stats/app_label_renamer.py: -------------------------------------------------------------------------------- 1 | # 2 | # This Source Code Form is subject to the terms of the Mozilla Public 3 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | # You can obtain one at http://mozilla.org/MPL/2.0/. 5 | # 6 | # Copyright (C) 2011-2014 Star2Billing S.L. 7 | # 8 | # The Initial Developer of the Original Code is 9 | # Arezqui Belaid 10 | # 11 | from django.contrib import admin 12 | from django.db.models.base import ModelBase 13 | try: 14 | from django.urls import resolve 15 | except ImportError: # Django<2.0 16 | from django.core.urlresolvers import resolve 17 | 18 | 19 | # TODO: Follow evolution of https://code.djangoproject.com/ticket/3591 20 | 21 | # Source link : http://django-notes.blogspot.in/2011/07/django-app-name-breadcrumbs-l10n.html 22 | class AppLabelRenamer(object): 23 | """ 24 | Rename app label and app breadcrumbs in admin 25 | """ 26 | def __init__(self, native_app_label, app_label): 27 | self.native_app_label = native_app_label 28 | self.app_label = app_label 29 | self.module = '.'.join([native_app_label, 'models']) 30 | 31 | class string_with_realoaded_title(str): 32 | ''' thanks to Ionel Maries Cristian for http://ionelmc.wordpress.com/2011/06/24/custom-app-names-in-the-django-admin/''' 33 | def __new__(cls, value, title): 34 | instance = str.__new__(cls, value) 35 | instance._title = title 36 | return instance 37 | 38 | def title(self): 39 | return self._title 40 | 41 | __copy__ = lambda self: self 42 | __deepcopy__ = lambda self, memodict: self 43 | 44 | def rename_app_label(self, f): 45 | app_label = self.app_label 46 | 47 | def rename_breadcrumbs(f): 48 | def wrap(self, *args, **kwargs): 49 | extra_context = kwargs.get('extra_context', {}) 50 | extra_context['app_label'] = app_label 51 | kwargs['extra_context'] = extra_context 52 | return f(self, *args, **kwargs) 53 | return wrap 54 | 55 | def wrap(model_or_iterable, admin_class=None, **option): 56 | if isinstance(model_or_iterable, ModelBase): 57 | model_or_iterable = [model_or_iterable] 58 | for model in model_or_iterable: 59 | if model.__module__ != self.module: 60 | continue 61 | if admin_class is None: 62 | admin_class = type(model.__name__ + 'Admin', (admin.ModelAdmin,), {}) 63 | admin_class.add_view = rename_breadcrumbs(admin_class.add_view) 64 | admin_class.change_view = rename_breadcrumbs(admin_class.change_view) 65 | admin_class.changelist_view = rename_breadcrumbs(admin_class.changelist_view) 66 | model._meta.app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label) 67 | return f(model, admin_class, **option) 68 | return wrap 69 | 70 | def rename_app_index(self, f): 71 | def wrap(request, app_label, extra_context=None): 72 | requested_app_label = resolve(request.path).kwargs.get('app_label', '') 73 | if requested_app_label and requested_app_label == self.native_app_label: 74 | app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label) 75 | else: 76 | app_label = requested_app_label 77 | return f(request, app_label, extra_context=None) 78 | return wrap 79 | 80 | def main(self): 81 | admin.site.register = self.rename_app_label(admin.site.register) 82 | admin.site.app_index = self.rename_app_index(admin.site.app_index) 83 | -------------------------------------------------------------------------------- /admin_tools_stats/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9 on 2015-12-13 11:29 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import jsonfield.fields 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='DashboardStats', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('graph_key', models.CharField(help_text='it needs to be one word unique. ex. auth, mygraph', max_length=90, unique=True, verbose_name='graph key')), 22 | ('graph_title', models.CharField(db_index=True, help_text='heading title of graph box', max_length=90, verbose_name='graph title')), 23 | ('model_app_name', models.CharField(help_text='ex. auth / dialer_cdr', max_length=90, verbose_name='app name')), 24 | ('model_name', models.CharField(help_text='ex. User', max_length=90, verbose_name='model name')), 25 | ('date_field_name', models.CharField(help_text='ex. date_joined', max_length=90, verbose_name='date field name')), 26 | ('operation_field_name', models.CharField(blank=True, help_text='The field you want to aggregate, ex. amount', max_length=90, null=True, verbose_name='Operate field name')), 27 | ('type_operation_field_name', models.CharField(blank=True, choices=[(b'Count', b'Count'), (b'Sum', b'Sum'), (b'Avg', b'Avg'), (b'Max', b'Max'), (b'Min', b'Min'), (b'StdDev', b'StdDev'), (b'Variance', b'Variance')], help_text='choose the type operation what you want to aggregate, ex. Sum', max_length=90, null=True, verbose_name='Choose Type operation')), 28 | ('is_visible', models.BooleanField(default=True, verbose_name='visible')), 29 | ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='date')), 30 | ('updated_date', models.DateTimeField(auto_now=True)), 31 | ], 32 | options={ 33 | 'db_table': 'dashboard_stats', 34 | 'verbose_name': 'dashboard stats', 35 | 'verbose_name_plural': 'dashboard stats', 36 | }, 37 | ), 38 | migrations.CreateModel( 39 | name='DashboardStatsCriteria', 40 | fields=[ 41 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 42 | ('criteria_name', models.CharField(db_index=True, help_text='it needs to be one word unique. Ex. status, yesno', max_length=90, verbose_name='criteria name')), 43 | ('criteria_fix_mapping', jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that will be used for the criteria', null=True, verbose_name='fixed criteria / value')), 44 | ('dynamic_criteria_field_name', models.CharField(blank=True, help_text='ex. for call records - disposition', max_length=90, null=True, verbose_name='dynamic criteria field name')), 45 | ('criteria_dynamic_mapping', jsonfield.fields.JSONField(blank=True, help_text='a JSON dictionary of key-value pairs that will be used for the criteria', null=True, verbose_name='dynamic criteria / value')), 46 | ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='date')), 47 | ('updated_date', models.DateTimeField(auto_now=True)), 48 | ], 49 | options={ 50 | 'db_table': 'dash_stats_criteria', 51 | 'verbose_name': 'dashboard stats criteria', 52 | 'verbose_name_plural': 'dashboard stats criteria', 53 | }, 54 | ), 55 | migrations.AddField( 56 | model_name='dashboardstats', 57 | name='criteria', 58 | field=models.ManyToManyField(blank=True, to='admin_tools_stats.DashboardStatsCriteria'), 59 | ), 60 | ] 61 | -------------------------------------------------------------------------------- /admin_tools_stats/south_migrations/0003_add_operation_field_name.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from south.utils import datetime_utils as datetime 3 | from south.db import db 4 | from south.v2 import SchemaMigration 5 | from django.db import models 6 | 7 | 8 | class Migration(SchemaMigration): 9 | 10 | def forwards(self, orm): 11 | # Deleting field 'DashboardStats.sum_field_name' 12 | db.delete_column(u'dashboard_stats', 'sum_field_name') 13 | 14 | # Adding field 'DashboardStats.operation_field_name' 15 | db.add_column(u'dashboard_stats', 'operation_field_name', 16 | self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True), 17 | keep_default=False) 18 | 19 | # Adding field 'DashboardStats.type_operation_field_name' 20 | db.add_column(u'dashboard_stats', 'type_operation_field_name', 21 | self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True), 22 | keep_default=False) 23 | 24 | 25 | def backwards(self, orm): 26 | # Adding field 'DashboardStats.sum_field_name' 27 | db.add_column(u'dashboard_stats', 'sum_field_name', 28 | self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True), 29 | keep_default=False) 30 | 31 | # Deleting field 'DashboardStats.operation_field_name' 32 | db.delete_column(u'dashboard_stats', 'operation_field_name') 33 | 34 | # Deleting field 'DashboardStats.type_operation_field_name' 35 | db.delete_column(u'dashboard_stats', 'type_operation_field_name') 36 | 37 | 38 | models = { 39 | u'admin_tools_stats.dashboardstats': { 40 | 'Meta': {'object_name': 'DashboardStats', 'db_table': "u'dashboard_stats'"}, 41 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 42 | 'criteria': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['admin_tools_stats.DashboardStatsCriteria']", 'null': 'True', 'blank': 'True'}), 43 | 'date_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 44 | 'graph_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '90'}), 45 | 'graph_title': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 46 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 47 | 'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 48 | 'model_app_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 49 | 'model_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 50 | 'operation_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 51 | 'type_operation_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 52 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 53 | }, 54 | u'admin_tools_stats.dashboardstatscriteria': { 55 | 'Meta': {'object_name': 'DashboardStatsCriteria', 'db_table': "u'dash_stats_criteria'"}, 56 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 57 | 'criteria_dynamic_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 58 | 'criteria_fix_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 59 | 'criteria_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 60 | 'dynamic_criteria_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 61 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 62 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 63 | } 64 | } 65 | 66 | complete_apps = ['admin_tools_stats'] -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 1.0.0 (2019-08-06) 5 | ------------------ 6 | 7 | * DistinctCount qualifier added 8 | * date/operate fields can now contain related reference 9 | * fix loading charts on page load 10 | 11 | 0.9.0 (2018-01-08) 12 | ------------------ 13 | 14 | * Count added 15 | * fix Travis configuration and Django versions in it 16 | * other fixes for Django 2.0 17 | * use djcacheutils for Python 3 compatibility 18 | 19 | 0.8.0 (2017-01-18) 20 | ------------------ 21 | 22 | * make possible to change dateformat of x axis 23 | * add example for dynamic criteria 24 | * test also dynamic criteria 25 | * use django-qsstats-magic that work with Python 3 in tests 26 | * test actual chart generation -> increase test coverage 27 | * fix: preserve criteria settings of other chart stats 28 | * fix duplicate id of dynamic criteria form 29 | * reduce size of generated code by reusing load_charts code in function 30 | * fix duplication of % sign in template svg tag 31 | * catch also TypeError in registration field 32 | * rename "Graph key" to "Graph identifier" to be more clear 33 | * use save_as=True in admin to allow easier copying of charts 34 | * allow to override day intervalse for graphs 35 | * reorganize testing to run coverage 36 | * remove old import code 37 | * checks of DashboardStats field values, report field errors by Django message framework 38 | 39 | 40 | 41 | 0.7.1 (2016-08-17) 42 | ------------------ 43 | 44 | * fix travis-ci tests Django & Python version 45 | 46 | 47 | 0.7.0 (2016-08-17) 48 | ------------------- 49 | 50 | * fixes for newer Django and Python versions 51 | * add Travis configuration file 52 | * allow to override get_registration_charts function 53 | * fix Python 3 compatibility 54 | * python manage.py bower_install creates the folder build for src 55 | 56 | 57 | 0.6.6 (2015-12-13) 58 | ------------------- 59 | 60 | * remove null=True on ManyToManyField 61 | 62 | 63 | 0.6.5 (2015-12-13) 64 | ------------------- 65 | 66 | * add migrations 67 | 68 | 69 | 0.6.4 (2015-12-12) 70 | ------------------- 71 | 72 | * fix bower_install creates a the folder build for src 73 | 74 | 75 | 0.6.3 (2015-12-11) 76 | ------------------- 77 | 78 | * support for django 1.9 - depreciated get_model 79 | 80 | 81 | 0.6.2 (2015-12-10) 82 | ------------------- 83 | 84 | * remove python-memcached from requirements 85 | 86 | 87 | 0.6.1 (2014-05-30) 88 | ------------------- 89 | 90 | * support of Aggregation functions 91 | 92 | 93 | 0.5.5 (2014-02-06) 94 | ------------------- 95 | 96 | * fix setup with requirement.txt file 97 | 98 | 99 | 0.5.4 (2014-02-06) 100 | ------------------- 101 | 102 | * get rid of dependencies 103 | 104 | 105 | 0.5.3 (2014-01-03) 106 | ------------------- 107 | 108 | * Fix js async loading with recent jquery version 109 | 110 | 111 | 0.5.2 (2014-01-01) 112 | ------------------- 113 | 114 | * Fix requirements to not force old version of jsonfield 115 | 116 | 117 | 0.5.1 (2013-10-11) 118 | ------------------- 119 | 120 | * Fix some bug on the tabs behavior and tooltip of the charts 121 | * Update documentation 122 | 123 | 124 | 0.5.0 (2013-10-09) 125 | ------------------- 126 | 127 | * Support for Django-NVD3 128 | 129 | 130 | 0.4.3 (2013-03-26) 131 | ------------------ 132 | 133 | * fix requirements - dep to django-admin-tools>=0.5.0 134 | 135 | 136 | 0.4.2 (2013-03-07) 137 | ------------------ 138 | 139 | * Update trans string 140 | 141 | 142 | 0.4.1 (2012-12-19) 143 | ------------------ 144 | 145 | * Fix requirement for switch2bill-common 146 | 147 | 148 | 0.4 (2012-11-19) 149 | ------------------ 150 | 151 | * Fix for Django 1.4 timezone support by vdboor (Diederik van der Boor) 152 | 153 | 154 | 0.3 (2012-10-03) 155 | ------------------ 156 | 157 | * Improve setup.py and update manifest 158 | * Update README.rst 159 | * Fix PEP8 160 | 161 | 162 | 0.2 (2011-05-22) 163 | ---------------- 164 | 165 | * Import project 166 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-admin-tools-stats.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-admin-tools-stats.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-admin-tools-stats" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-admin-tools-stats" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /demoproject/dashboard.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file was generated with the customdashboard management command, it 3 | contains the two classes for the main dashboard and app index dashboard. 4 | You can customize these classes as you want. 5 | 6 | To activate your index dashboard add the following to your settings.py:: 7 | ADMIN_TOOLS_INDEX_DASHBOARD = 'demoproject.dashboard.CustomIndexDashboard' 8 | 9 | And to activate the app index dashboard:: 10 | ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'demoproject.dashboard.CustomAppIndexDashboard' 11 | """ 12 | 13 | from django.utils.translation import ugettext_lazy as _ 14 | try: 15 | from django.urls import reverse 16 | except ImportError: # Django<2.0 17 | from django.core.urlresolvers import reverse 18 | 19 | from admin_tools.dashboard import modules, Dashboard, AppIndexDashboard 20 | from admin_tools.utils import get_admin_site_name 21 | from admin_tools_stats.modules import DashboardCharts, get_active_graph 22 | 23 | 24 | class CustomIndexDashboard(Dashboard): 25 | """ 26 | Custom index dashboard for demoproject. 27 | """ 28 | def init_with_context(self, context): 29 | site_name = get_admin_site_name(context) 30 | # append a link list module for "quick links" 31 | self.children.append(modules.LinkList( 32 | _('Quick links'), 33 | layout='inline', 34 | draggable=False, 35 | deletable=False, 36 | collapsible=False, 37 | children=[ 38 | [_('Return to site'), '/'], 39 | [_('Change password'), 40 | reverse('%s:password_change' % site_name)], 41 | [_('Log out'), reverse('%s:logout' % site_name)], 42 | ] 43 | )) 44 | 45 | # append an app list module for "Applications" 46 | self.children.append(modules.AppList( 47 | _('Applications'), 48 | exclude=('django.contrib.*',), 49 | )) 50 | 51 | # append an app list module for "Administration" 52 | self.children.append(modules.AppList( 53 | _('Administration'), 54 | models=('django.contrib.*',), 55 | )) 56 | 57 | # append a recent actions module 58 | self.children.append(modules.RecentActions(_('Recent Actions'), 5)) 59 | 60 | # append a feed module 61 | self.children.append(modules.Feed( 62 | _('Latest Django News'), 63 | feed_url='http://www.djangoproject.com/rss/weblog/', 64 | limit=5 65 | )) 66 | 67 | # append an app list module 68 | self.children.append(modules.AppList( 69 | _('Dashboard Stats Settings'), 70 | models=('admin_tools_stats.*', ), 71 | )) 72 | 73 | # Copy following code into your custom dashboard 74 | # append following code after recent actions module or 75 | # a link list module for "quick links" 76 | graph_list = get_active_graph() 77 | for i in graph_list: 78 | kwargs = {} 79 | kwargs['require_chart_jscss'] = True 80 | kwargs['graph_key'] = i.graph_key 81 | 82 | for key in context['request'].POST: 83 | if key.startswith('select_box_'): 84 | kwargs[key] = context['request'].POST[key] 85 | 86 | self.children.append(DashboardCharts(**kwargs)) 87 | 88 | # append another link list module for "support". 89 | self.children.append(modules.LinkList( 90 | _('Support'), 91 | children=[ 92 | { 93 | 'title': _('Django documentation'), 94 | 'url': 'http://docs.djangoproject.com/', 95 | 'external': True, 96 | }, 97 | { 98 | 'title': _('Django "django-users" mailing list'), 99 | 'url': 'http://groups.google.com/group/django-users', 100 | 'external': True, 101 | }, 102 | { 103 | 'title': _('Django irc channel'), 104 | 'url': 'irc://irc.freenode.net/django', 105 | 'external': True, 106 | }, 107 | ] 108 | )) 109 | 110 | 111 | class CustomAppIndexDashboard(AppIndexDashboard): 112 | """ 113 | Custom app index dashboard for demoproject. 114 | """ 115 | 116 | # we disable title because its redundant with the model list module 117 | title = '' 118 | 119 | def __init__(self, *args, **kwargs): 120 | AppIndexDashboard.__init__(self, *args, **kwargs) 121 | 122 | # append a model list module and a recent actions module 123 | self.children += [ 124 | modules.ModelList(self.app_title, self.models), 125 | modules.RecentActions( 126 | _('Recent Actions'), 127 | include_list=self.get_app_content_types(), 128 | limit=5 129 | ) 130 | ] 131 | 132 | def init_with_context(self, context): 133 | """ 134 | Use this method if you need to access the request context. 135 | """ 136 | return super(CustomAppIndexDashboard, self).init_with_context(context) 137 | -------------------------------------------------------------------------------- /admin_tools_stats/tests.py: -------------------------------------------------------------------------------- 1 | # 2 | # This Source Code Form is subject to the terms of the Mozilla Public 3 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | # You can obtain one at http://mozilla.org/MPL/2.0/. 5 | # 6 | # Copyright (C) 2011-2014 Star2Billing S.L. 7 | # 8 | # The Initial Developer of the Original Code is 9 | # Arezqui Belaid 10 | # 11 | 12 | import django 13 | 14 | from django.test import TestCase 15 | from django.core.exceptions import ValidationError 16 | from admin_tools_stats.models import DashboardStatsCriteria, DashboardStats 17 | from admin_tools_stats.utils import BaseAuthenticatedClient 18 | 19 | 20 | class AdminToolsStatsAdminInterfaceTestCase(BaseAuthenticatedClient): 21 | """ 22 | Test cases for django-admin-tools-stats Admin Interface 23 | """ 24 | 25 | def test_admin_tools_stats_dashboardstats(self): 26 | """Test function to check dashboardstats admin pages""" 27 | response = self.client.get('/admin/admin_tools_stats/') 28 | self.assertEqual(response.status_code, 200) 29 | response = self.client.get('/admin/admin_tools_stats/dashboardstats/') 30 | self.assertEqual(response.status_code, 200) 31 | 32 | def test_admin_tools_stats_dashboardstatscriteria(self): 33 | """Test function to check dashboardstatscriteria admin pages""" 34 | response = \ 35 | self.client.get('/admin/admin_tools_stats/dashboardstatscriteria/') 36 | self.assertEqual(response.status_code, 200) 37 | 38 | 39 | class AdminToolsStatsAdminCharts(BaseAuthenticatedClient): 40 | fixtures = ['test_data', 'auth_user'] 41 | 42 | if django.VERSION >= (1,8,0): 43 | def test_admin_dashboard_page(self): 44 | """Test function to check dashboardstatscriteria admin pages""" 45 | response = self.client.get('/admin/') 46 | self.assertContains( 47 | response, 48 | '

User graph

', 49 | html=True, 50 | ) 51 | self.assertContains( 52 | response, 53 | '

User logged in graph

', 54 | html=True, 55 | ) 56 | self.assertContains( 57 | response, 58 | '', 59 | html=True, 60 | ) 61 | self.assertContains( 62 | response, 63 | '', 64 | html=True, 65 | ) 66 | self.assertContains( 67 | response, 68 | '', 69 | html=True, 70 | ) 71 | 72 | def test_admin_dashboard_page_post(self): 73 | """Test function to check dashboardstatscriteria admin pages""" 74 | response = self.client.post('/admin/', {'select_box_user_graph': 'true'}) 75 | self.assertContains( 76 | response, 77 | '', 78 | html=True, 79 | ) 80 | self.assertContains( 81 | response, 82 | '', 83 | html=True, 84 | ) 85 | 86 | 87 | class AdminToolsStatsModel(TestCase): 88 | """ 89 | Test DashboardStatsCriteria, DashboardStats models 90 | """ 91 | def setUp(self): 92 | # DashboardStatsCriteria model 93 | self.dashboard_stats_criteria = DashboardStatsCriteria( 94 | criteria_name="call_type", 95 | criteria_fix_mapping='', 96 | dynamic_criteria_field_name='disposition', 97 | criteria_dynamic_mapping={ 98 | "INVALIDARGS": "INVALIDARGS", 99 | "BUSY": "BUSY", 100 | "TORTURE": "TORTURE", 101 | "ANSWER": "ANSWER", 102 | "DONTCALL": "DONTCALL", 103 | "FORBIDDEN": "FORBIDDEN", 104 | "NOROUTE": "NOROUTE", 105 | "CHANUNAVAIL": "CHANUNAVAIL", 106 | "NOANSWER": "NOANSWER", 107 | "CONGESTION": "CONGESTION", 108 | "CANCEL": "CANCEL" 109 | }, 110 | ) 111 | self.dashboard_stats_criteria.save() 112 | self.assertEqual( 113 | self.dashboard_stats_criteria.__str__(), 'call_type') 114 | 115 | # DashboardStats model 116 | self.dashboard_stats = DashboardStats( 117 | graph_key='user_graph_test', 118 | graph_title='User graph', 119 | model_app_name='auth', 120 | model_name='User', 121 | date_field_name='date_joined', 122 | is_visible=1, 123 | ) 124 | self.dashboard_stats.save() 125 | self.dashboard_stats.criteria.add(self.dashboard_stats_criteria) 126 | self.dashboard_stats.save() 127 | with self.assertRaises(ValidationError) as e: 128 | self.dashboard_stats.clean() 129 | self.assertEqual(e.exception.message_dict, {}) 130 | self.assertEqual(self.dashboard_stats.__str__(), 'user_graph_test') 131 | 132 | def test_dashboard_criteria(self): 133 | self.assertEqual( 134 | self.dashboard_stats_criteria.criteria_name, "call_type") 135 | self.assertEqual(self.dashboard_stats.graph_key, 'user_graph_test') 136 | 137 | def teardown(self): 138 | self.dashboard_stats_criteria.delete() 139 | self.dashboard_stats.delete() 140 | -------------------------------------------------------------------------------- /admin_tools_stats/south_migrations/0001_initial_migration.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from south.utils import datetime_utils as datetime 3 | from south.db import db 4 | from south.v2 import SchemaMigration 5 | from django.db import models 6 | 7 | 8 | class Migration(SchemaMigration): 9 | 10 | def forwards(self, orm): 11 | # Adding model 'DashboardStatsCriteria' 12 | db.create_table(u'dash_stats_criteria', ( 13 | (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 14 | ('criteria_name', self.gf('django.db.models.fields.CharField')(max_length=90, db_index=True)), 15 | ('criteria_fix_mapping', self.gf('jsonfield.fields.JSONField')(null=True, blank=True)), 16 | ('dynamic_criteria_field_name', self.gf('django.db.models.fields.CharField')(max_length=90, null=True, blank=True)), 17 | ('criteria_dynamic_mapping', self.gf('jsonfield.fields.JSONField')(null=True, blank=True)), 18 | ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), 19 | ('updated_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), 20 | )) 21 | db.send_create_signal(u'admin_tools_stats', ['DashboardStatsCriteria']) 22 | 23 | # Adding model 'DashboardStats' 24 | db.create_table(u'dashboard_stats', ( 25 | (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 26 | ('graph_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=90)), 27 | ('graph_title', self.gf('django.db.models.fields.CharField')(max_length=90, db_index=True)), 28 | ('model_app_name', self.gf('django.db.models.fields.CharField')(max_length=90)), 29 | ('model_name', self.gf('django.db.models.fields.CharField')(max_length=90)), 30 | ('date_field_name', self.gf('django.db.models.fields.CharField')(max_length=90)), 31 | ('is_visible', self.gf('django.db.models.fields.BooleanField')(default=True)), 32 | ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), 33 | ('updated_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), 34 | )) 35 | db.send_create_signal(u'admin_tools_stats', ['DashboardStats']) 36 | 37 | # Adding M2M table for field criteria on 'DashboardStats' 38 | m2m_table_name = db.shorten_name(u'dashboard_stats_criteria') 39 | db.create_table(m2m_table_name, ( 40 | ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), 41 | ('dashboardstats', models.ForeignKey(orm[u'admin_tools_stats.dashboardstats'], null=False)), 42 | ('dashboardstatscriteria', models.ForeignKey(orm[u'admin_tools_stats.dashboardstatscriteria'], null=False)) 43 | )) 44 | db.create_unique(m2m_table_name, ['dashboardstats_id', 'dashboardstatscriteria_id']) 45 | 46 | 47 | def backwards(self, orm): 48 | # Deleting model 'DashboardStatsCriteria' 49 | db.delete_table(u'dash_stats_criteria') 50 | 51 | # Deleting model 'DashboardStats' 52 | db.delete_table(u'dashboard_stats') 53 | 54 | # Removing M2M table for field criteria on 'DashboardStats' 55 | db.delete_table(db.shorten_name(u'dashboard_stats_criteria')) 56 | 57 | 58 | models = { 59 | u'admin_tools_stats.dashboardstats': { 60 | 'Meta': {'object_name': 'DashboardStats', 'db_table': "u'dashboard_stats'"}, 61 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 62 | 'criteria': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['admin_tools_stats.DashboardStatsCriteria']", 'null': 'True', 'blank': 'True'}), 63 | 'date_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 64 | 'graph_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '90'}), 65 | 'graph_title': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 66 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 67 | 'is_visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 68 | 'model_app_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 69 | 'model_name': ('django.db.models.fields.CharField', [], {'max_length': '90'}), 70 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 71 | }, 72 | u'admin_tools_stats.dashboardstatscriteria': { 73 | 'Meta': {'object_name': 'DashboardStatsCriteria', 'db_table': "u'dash_stats_criteria'"}, 74 | 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 75 | 'criteria_dynamic_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 76 | 'criteria_fix_mapping': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 77 | 'criteria_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'db_index': 'True'}), 78 | 'dynamic_criteria_field_name': ('django.db.models.fields.CharField', [], {'max_length': '90', 'null': 'True', 'blank': 'True'}), 79 | u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 80 | 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) 81 | } 82 | } 83 | 84 | complete_apps = ['admin_tools_stats'] -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | NOTE: This project was rewritten to be more flexible and to work with common Django admin and released as `django-admin-charts `_. The `django-admin-charts` project is backward-compatible with `django-admin-tools-stats`, so you can migrate to that. All development and maintanence continues on `django-admin-charts` repository. 2 | 3 | 4 | Django-admin-tools-stats 5 | ------------------------ 6 | 7 | :Description: Django-admin module to create charts and stats in your dashboard 8 | :Documentation: http://django-admin-tools-stats.readthedocs.org/en/latest/ 9 | 10 | .. image:: https://travis-ci.org/areski/django-admin-tools-stats.svg?branch=master 11 | :target: https://travis-ci.org/areski/django-admin-tools-stats 12 | 13 | .. image:: https://img.shields.io/pypi/v/django-admin-tools-stats.svg 14 | :target: https://pypi.python.org/pypi/django-admin-tools-stats/ 15 | :alt: Latest Version 16 | 17 | .. image:: https://img.shields.io/pypi/dm/django-admin-tools-stats.svg 18 | :target: https://pypi.python.org/pypi/django-admin-tools-stats/ 19 | :alt: Downloads 20 | 21 | .. image:: https://img.shields.io/pypi/pyversions/django-admin-tools-stats.svg 22 | :target: https://pypi.python.org/pypi/django-admin-tools-stats/ 23 | :alt: Supported Python versions 24 | 25 | .. image:: https://img.shields.io/pypi/l/django-admin-tools-stats.svg 26 | :target: https://pypi.python.org/pypi/django-admin-tools-stats/ 27 | :alt: License 28 | 29 | 30 | Django-admin-tools-stats is a Django admin module that allow you to create easily charts on your dashboard based on specific models and criterias. 31 | 32 | It will query your models and provide reporting and statistics graphs, simple to read and display on your Dashboard. 33 | 34 | .. image:: https://github.com/areski/django-admin-tools-stats/raw/master/docs/source/_static/admin_dashboard.png 35 | 36 | 37 | Installation 38 | ------------ 39 | 40 | Install, upgrade and uninstall django-admin-tools-stats with these commands:: 41 | 42 | $ pip install django-admin-tools-stats 43 | 44 | 45 | Dependencies 46 | ------------ 47 | 48 | django-admin-tools-stats is a django based application, the major requirements are : 49 | 50 | - python-dateutil 51 | - django-jsonfield 52 | - django-qsstats-magic 53 | - django-cache-utils 54 | - django-admin-tools 55 | - django-nvd3 56 | - django-bower 57 | 58 | 59 | Configure 60 | --------- 61 | 62 | - Configure ``admin_tools`` 63 | - Configure ``django-bower`` 64 | 65 | - Add ``django-bower`` to INSTALLED_APPS in settings.py:: 66 | 67 | INSTALLED_APPS = ( 68 | ... 69 | 'djangobower' 70 | ) 71 | 72 | - Add the following properties to you settings.py file:: 73 | 74 | # Specifie path to components root (you need to use absolute path) 75 | BOWER_COMPONENTS_ROOT = os.path.join(PROJECT_ROOT, 'components') 76 | 77 | 78 | BOWER_INSTALLED_APPS = ( 79 | 'jquery#3.4.1', 80 | 'jquery-ui#1.12.1', 81 | 'd3#3.3.13', 82 | 'nvd3#1.7.1', 83 | ) 84 | 85 | - Add django-bower finder to your static file finders:: 86 | 87 | STATICFILES_FINDERS = ( 88 | ... 89 | 'djangobower.finders.BowerFinder', 90 | ) 91 | 92 | - Run the following commands. These will download nvd3.js and its dependencies using bower and throw them in to you static folder for access by your application:: 93 | 94 | $ python manage.py bower_install 95 | $ python manage.py collectstatic 96 | 97 | - Add ``admin_tools_stats`` & ``django_nvd3`` into INSTALLED_APPS in settings.py:: 98 | 99 | INSTALLED_APPS = ( 100 | ... 101 | 'admin_tools_stats', 102 | 'django_nvd3', 103 | ) 104 | 105 | - Add following code to dashboard.py:: 106 | 107 | from admin_tools_stats.modules import DashboardCharts, get_active_graph 108 | 109 | # append an app list module 110 | self.children.append(modules.AppList( 111 | _('Dashboard Stats Settings'), 112 | models=('admin_tools_stats.*', ), 113 | )) 114 | 115 | # Copy following code into your custom dashboard 116 | # append following code after recent actions module or 117 | # a link list module for "quick links" 118 | graph_list = get_active_graph() 119 | for i in graph_list: 120 | kwargs = {} 121 | kwargs['require_chart_jscss'] = True 122 | kwargs['graph_key'] = i.graph_key 123 | 124 | for key in context['request'].POST: 125 | if key.startswith('select_box_'): 126 | kwargs[key] = context['request'].POST[key] 127 | 128 | self.children.append(DashboardCharts(**kwargs)) 129 | 130 | - To create the tables needed by Django-admin-tools-stats, run the following command:: 131 | 132 | $ python manage.py syncdb 133 | 134 | - You may also need to add some includes to your template admin base, see an example on the demo project: 135 | 136 | demoproject/demoproject/templates/admin/base_site.html 137 | 138 | - Open admin panel, configure ``Dashboard Stats Criteria`` & ``Dashboard Stats respectively`` 139 | 140 | 141 | Contributing 142 | ------------ 143 | 144 | If you've found a bug, add a feature or improve django-admin-tools-stats and 145 | think it is useful then please consider contributing. 146 | Patches, pull requests or just suggestions are always welcome! 147 | 148 | Source code: http://github.com/areski/django-admin-tools-stats 149 | 150 | Bug tracker: https://github.com/areski/django-admin-tools-stats/issues 151 | 152 | 153 | Documentation 154 | ------------- 155 | 156 | Documentation is available on 'Read the Docs': 157 | http://readthedocs.org/docs/django-admin-tools-stats/ 158 | 159 | 160 | License 161 | ------- 162 | 163 | Copyright (c) 2011-2017 Star2Billing S.L. 164 | 165 | django-admin-tools-stats is licensed under MIT, see `MIT-LICENSE.txt`. 166 | -------------------------------------------------------------------------------- /admin_tools_stats/models.py: -------------------------------------------------------------------------------- 1 | # 2 | # This Source Code Form is subject to the terms of the Mozilla Public 3 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | # You can obtain one at http://mozilla.org/MPL/2.0/. 5 | # 6 | # Copyright (C) 2011-2014 Star2Billing S.L. 7 | # 8 | # The Initial Developer of the Original Code is 9 | # Arezqui Belaid 10 | # 11 | 12 | from django.db import models 13 | from django.core.exceptions import FieldError, ValidationError 14 | from django.utils.encoding import python_2_unicode_compatible 15 | from django.utils.translation import ugettext_lazy as _ 16 | from django.apps import apps 17 | import jsonfield.fields 18 | 19 | operation = ( 20 | ('DistinctCount', 'DistinctCount'), 21 | ('Count', 'Count'), 22 | ('Sum', 'Sum'), 23 | ('Avg', 'Avg'), 24 | ('Max', 'Max'), 25 | ('Min', 'Min'), 26 | ('StdDev', 'StdDev'), 27 | ('Variance', 'Variance'), 28 | ) 29 | 30 | 31 | @python_2_unicode_compatible 32 | class DashboardStatsCriteria(models.Model): 33 | """ 34 | To configure criteria for dashboard graphs 35 | 36 | **Attributes**: 37 | 38 | * ``criteria_name`` - Unique word . 39 | * ``criteria_fix_mapping`` - JSON data key-value pairs. 40 | * ``dynamic_criteria_field_name`` - Dynamic criteria field. 41 | * ``criteria_dynamic_mapping`` - JSON data key-value pairs. 42 | * ``created_date`` - record created date. 43 | * ``updated_date`` - record updated date. 44 | 45 | **Name of DB table**: dash_stats_criteria 46 | """ 47 | criteria_name = models.CharField(max_length=90, db_index=True, 48 | verbose_name=_('criteria name'), 49 | help_text=_("it needs to be one word unique. Ex. status, yesno")) 50 | criteria_fix_mapping = jsonfield.fields.JSONField( 51 | null=True, blank=True, 52 | verbose_name=_("fixed criteria / value"), 53 | help_text=_("a JSON dictionary of key-value pairs that will be used for the criteria")) 54 | dynamic_criteria_field_name = models.CharField( 55 | max_length=90, blank=True, null=True, 56 | verbose_name=_("dynamic criteria field name"), 57 | help_text=_("ex. for call records - disposition")) 58 | criteria_dynamic_mapping = jsonfield.fields.JSONField( 59 | null=True, blank=True, 60 | verbose_name=_("dynamic criteria / value"), 61 | help_text=_( 62 | "a JSON dictionary of key-value pairs that will be used for the criteria" 63 | " Ex. \"{'false': 'Inactive', 'true': 'Active'}\"", 64 | ), 65 | ) 66 | created_date = models.DateTimeField(auto_now_add=True, verbose_name=_('date')) 67 | updated_date = models.DateTimeField(auto_now=True) 68 | 69 | class Meta: 70 | app_label = "admin_tools_stats" 71 | db_table = u'dash_stats_criteria' 72 | verbose_name = _("dashboard stats criteria") 73 | verbose_name_plural = _("dashboard stats criteria") 74 | 75 | def __str__(self): 76 | return u"%s" % self.criteria_name 77 | 78 | 79 | @python_2_unicode_compatible 80 | class DashboardStats(models.Model): 81 | """To configure graphs for dashboard 82 | 83 | **Attributes**: 84 | 85 | * ``graph_key`` - unique graph name. 86 | * ``graph_title`` - graph title. 87 | * ``model_app_name`` - App name of model. 88 | * ``model_name`` - model name. 89 | * ``date_field_name`` - Date field of model_name. 90 | * ``criteria`` - many-to-many relationship. 91 | * ``is_visible`` - enable/disable. 92 | * ``created_date`` - record created date. 93 | * ``updated_date`` - record updated date. 94 | 95 | **Name of DB table**: dashboard_stats 96 | """ 97 | graph_key = models.CharField(unique=True, max_length=90, 98 | verbose_name=_('graph identifier'), 99 | help_text=_("it needs to be one word unique. ex. auth, mygraph")) 100 | graph_title = models.CharField(max_length=90, db_index=True, 101 | verbose_name=_('graph title'), 102 | help_text=_("heading title of graph box")) 103 | model_app_name = models.CharField(max_length=90, verbose_name=_('app name'), 104 | help_text=_("ex. auth / dialer_cdr")) 105 | model_name = models.CharField(max_length=90, verbose_name=_('model name'), 106 | help_text=_("ex. User")) 107 | date_field_name = models.CharField(max_length=90, verbose_name=_("date field name"), 108 | help_text=_("ex. date_joined, invitation__invitation_date")) 109 | user_field_name = models.CharField(max_length=90, verbose_name=_("user field name"), 110 | null=True, blank=True, 111 | help_text=_("ex. owner, invitation__owner")) 112 | operation_field_name = models.CharField(max_length=90, verbose_name=_("Operate field name"), 113 | null=True, blank=True, 114 | help_text=_("The field you want to aggregate, ex. amount, salaries__total_income")) 115 | type_operation_field_name = models.CharField(max_length=90, verbose_name=_("Choose Type operation"), 116 | null=True, blank=True, choices=operation, 117 | help_text=_("choose the type operation what you want to aggregate, ex. Sum")) 118 | criteria = models.ManyToManyField(DashboardStatsCriteria, blank=True) 119 | is_visible = models.BooleanField(default=True, verbose_name=_('visible')) 120 | created_date = models.DateTimeField(auto_now_add=True, verbose_name=_('date')) 121 | updated_date = models.DateTimeField(auto_now=True) 122 | 123 | class Meta: 124 | app_label = "admin_tools_stats" 125 | db_table = u'dashboard_stats' 126 | verbose_name = _("dashboard stats") 127 | verbose_name_plural = _("dashboard stats") 128 | 129 | def clean(self, *args, **kwargs): 130 | errors = {} 131 | model = None 132 | try: 133 | apps.get_app_config(self.model_app_name) 134 | except LookupError as e: 135 | errors['model_app_name'] = str(e) 136 | 137 | try: 138 | model = apps.get_model(self.model_app_name, self.model_name) 139 | except LookupError as e: 140 | errors['model_name'] = str(e) 141 | 142 | try: 143 | if model and self.operation_field_name: 144 | model.objects.all().query.resolve_ref(self.operation_field_name) 145 | except FieldError as e: 146 | errors['operation_field_name'] = str(e) 147 | 148 | try: 149 | if model and self.date_field_name: 150 | model.objects.all().query.resolve_ref(self.date_field_name) 151 | except FieldError as e: 152 | errors['date_field_name'] = str(e) 153 | 154 | raise ValidationError(errors) 155 | return super(DashboardStats, self).clean(*args, **kwargs) 156 | 157 | 158 | 159 | def __str__(self): 160 | return u"%s" % self.graph_key 161 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-admin-tools-stats documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Sep 7 13:28:47 2011. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | #APP_DIR = os.path.normpath(os.path.join(os.getcwd(), '../..')) 21 | #sys.path.insert(0, APP_DIR) 22 | 23 | #import settings 24 | #from django.core.management import setup_environ 25 | #setup_environ(settings) 26 | # -- General configuration ----------------------------------------------------- 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | #needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be extensions 32 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 33 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage'] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ['_templates'] 37 | 38 | # The suffix of source filenames. 39 | source_suffix = '.rst' 40 | 41 | # The encoding of source files. 42 | #source_encoding = 'utf-8-sig' 43 | 44 | # The master toctree document. 45 | master_doc = 'index' 46 | 47 | # General information about the project. 48 | project = u'django-admin-tools-stats' 49 | copyright = u'2011-2014, Arezqui Belaid' 50 | 51 | # The version info for the project you're documenting, acts as replacement for 52 | # |version| and |release|, also used in various other places throughout the 53 | # built documents. 54 | # 55 | # The short X.Y version. 56 | version = '0.9.0' 57 | # The full version, including alpha/beta/rc tags. 58 | release = version 59 | 60 | # The language for content autogenerated by Sphinx. Refer to documentation 61 | # for a list of supported languages. 62 | #language = None 63 | 64 | # There are two options for replacing |today|: either, you set today to some 65 | # non-false value, then it is used: 66 | #today = '' 67 | # Else, today_fmt is used as the format for a strftime call. 68 | #today_fmt = '%B %d, %Y' 69 | 70 | # List of patterns, relative to source directory, that match files and 71 | # directories to ignore when looking for source files. 72 | exclude_patterns = ['_build'] 73 | 74 | # The reST default role (used for this markup: `text`) to use for all documents. 75 | #default_role = None 76 | 77 | # If true, '()' will be appended to :func: etc. cross-reference text. 78 | #add_function_parentheses = True 79 | 80 | # If true, the current module name will be prepended to all description 81 | # unit titles (such as .. function::). 82 | #add_module_names = True 83 | 84 | # If true, sectionauthor and moduleauthor directives will be shown in the 85 | # output. They are ignored by default. 86 | #show_authors = False 87 | 88 | # The name of the Pygments (syntax highlighting) style to use. 89 | pygments_style = 'sphinx' 90 | 91 | # A list of ignored prefixes for module index sorting. 92 | #modindex_common_prefix = [] 93 | 94 | 95 | # -- Options for HTML output --------------------------------------------------- 96 | 97 | # The theme to use for HTML and HTML Help pages. See the documentation for 98 | # a list of builtin themes. 99 | html_theme = 'default' 100 | 101 | # Theme options are theme-specific and customize the look and feel of a theme 102 | # further. For a list of options available for each theme, see the 103 | # documentation. 104 | #html_theme_options = {} 105 | 106 | # Add any paths that contain custom themes here, relative to this directory. 107 | #html_theme_path = [] 108 | 109 | # The name for this set of Sphinx documents. If None, it defaults to 110 | # " v documentation". 111 | #html_title = None 112 | 113 | # A shorter title for the navigation bar. Default is the same as html_title. 114 | #html_short_title = None 115 | 116 | # The name of an image file (relative to this directory) to place at the top 117 | # of the sidebar. 118 | #html_logo = None 119 | 120 | # The name of an image file (within the static path) to use as favicon of the 121 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 122 | # pixels large. 123 | #html_favicon = None 124 | 125 | # Add any paths that contain custom static files (such as style sheets) here, 126 | # relative to this directory. They are copied after the builtin static files, 127 | # so a file named "default.css" will overwrite the builtin "default.css". 128 | html_static_path = ['_static'] 129 | 130 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 131 | # using the given strftime format. 132 | #html_last_updated_fmt = '%b %d, %Y' 133 | 134 | # If true, SmartyPants will be used to convert quotes and dashes to 135 | # typographically correct entities. 136 | #html_use_smartypants = True 137 | 138 | # Custom sidebar templates, maps document names to template names. 139 | #html_sidebars = {} 140 | 141 | # Additional templates that should be rendered to pages, maps page names to 142 | # template names. 143 | #html_additional_pages = {} 144 | 145 | # If false, no module index is generated. 146 | #html_domain_indices = True 147 | 148 | # If false, no index is generated. 149 | #html_use_index = True 150 | 151 | # If true, the index is split into individual pages for each letter. 152 | #html_split_index = False 153 | 154 | # If true, links to the reST sources are added to the pages. 155 | #html_show_sourcelink = True 156 | 157 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 158 | #html_show_sphinx = True 159 | 160 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 161 | #html_show_copyright = True 162 | 163 | # If true, an OpenSearch description file will be output, and all pages will 164 | # contain a tag referring to it. The value of this option must be the 165 | # base URL from which the finished HTML is served. 166 | #html_use_opensearch = '' 167 | 168 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 169 | #html_file_suffix = None 170 | 171 | # Output file base name for HTML help builder. 172 | htmlhelp_basename = 'django-admin-tools-stats-doc' 173 | 174 | 175 | # -- Options for LaTeX output -------------------------------------------------- 176 | 177 | # The paper size ('letter' or 'a4'). 178 | #latex_paper_size = 'letter' 179 | 180 | # The font size ('10pt', '11pt' or '12pt'). 181 | #latex_font_size = '10pt' 182 | 183 | # Grouping the document tree into LaTeX files. List of tuples 184 | # (source start file, target name, title, author, documentclass [howto/manual]). 185 | latex_documents = [ 186 | ('index.html', 'django-admin-tools-stats.tex', u'django-admin-tools-stats Documentation', 187 | u'Arezqui Belaid', 'manual'), 188 | ] 189 | 190 | # The name of an image file (relative to this directory) to place at the top of 191 | # the title page. 192 | #latex_logo = None 193 | 194 | # For "manual" documents, if this is true, then toplevel headings are parts, 195 | # not chapters. 196 | #latex_use_parts = False 197 | 198 | # If true, show page references after internal links. 199 | #latex_show_pagerefs = False 200 | 201 | # If true, show URL addresses after external links. 202 | #latex_show_urls = False 203 | 204 | # Additional stuff for the LaTeX preamble. 205 | #latex_preamble = '' 206 | 207 | # Documents to append as an appendix to all manuals. 208 | #latex_appendices = [] 209 | 210 | # If false, no module index is generated. 211 | #latex_domain_indices = True 212 | 213 | 214 | # -- Options for manual page output -------------------------------------------- 215 | 216 | # One entry per manual page. List of tuples 217 | # (source start file, name, description, authors, manual section). 218 | man_pages = [ 219 | ('index', 'django-admin-tools-stats', u'django-admin-tools-stats Documentation', 220 | [u'Arezqui Belaid'], 1) 221 | ] 222 | -------------------------------------------------------------------------------- /demoproject/demoproject/settings.py: -------------------------------------------------------------------------------- 1 | # Django settings for demoproject project. 2 | 3 | import os 4 | 5 | DEBUG = True 6 | 7 | APPLICATION_DIR = os.path.dirname(globals()['__file__']) 8 | 9 | PROJECT_ROOT = os.path.abspath( 10 | os.path.join(os.path.dirname(__file__), ".."), 11 | ) 12 | 13 | ADMINS = ( 14 | # ('Your Name', 'your_email@example.com'), 15 | ) 16 | 17 | MANAGERS = ADMINS 18 | 19 | DATABASES = { 20 | 'default': { 21 | 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 22 | 'NAME': 'demoproject.db', # Or path to database file if using sqlite3. 23 | # The following settings are not used with sqlite3: 24 | 'USER': '', 25 | 'PASSWORD': '', 26 | 'HOST': '', 27 | 'PORT': '', # Set to empty string for default. 28 | } 29 | } 30 | 31 | # Hosts/domain names that are valid for this site; required if DEBUG is False 32 | # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts 33 | ALLOWED_HOSTS = [] 34 | 35 | # Local time zone for this installation. Choices can be found here: 36 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 37 | # although not all choices may be available on all operating systems. 38 | # In a Windows environment this must be set to your system time zone. 39 | TIME_ZONE = 'America/Chicago' 40 | 41 | # Language code for this installation. All choices can be found here: 42 | # http://www.i18nguy.com/unicode/language-identifiers.html 43 | LANGUAGE_CODE = 'en-us' 44 | 45 | SITE_ID = 1 46 | 47 | # If you set this to False, Django will make some optimizations so as not 48 | # to load the internationalization machinery. 49 | USE_I18N = True 50 | 51 | # If you set this to False, Django will not format dates, numbers and 52 | # calendars according to the current locale. 53 | USE_L10N = True 54 | 55 | # If you set this to False, Django will not use timezone-aware datetimes. 56 | USE_TZ = True 57 | 58 | # Absolute filesystem path to the directory that will hold user-uploaded files. 59 | # Example: "/var/www/example.com/media/" 60 | MEDIA_ROOT = '' 61 | 62 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 63 | # trailing slash. 64 | # Examples: "http://example.com/media/", "http://media.example.com/" 65 | MEDIA_URL = '' 66 | 67 | # Absolute path to the directory static files should be collected to. 68 | # Don't put anything in this directory yourself; store your static files 69 | # in apps' "static/" subdirectories and in STATICFILES_DIRS. 70 | # Example: "/var/www/example.com/static/" 71 | STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') 72 | 73 | # URL prefix for static files. 74 | # Example: "http://example.com/static/", "http://static.example.com/" 75 | STATIC_URL = '/static/' 76 | 77 | # Additional locations of static files 78 | STATICFILES_DIRS = ( 79 | # Put strings here, like "/home/html/static" or "C:/www/django/static". 80 | # Always use forward slashes, even on Windows. 81 | # Don't forget to use absolute paths, not relative paths. 82 | ) 83 | 84 | # List of finder classes that know how to find static files in 85 | # various locations. 86 | STATICFILES_FINDERS = ( 87 | 'django.contrib.staticfiles.finders.FileSystemFinder', 88 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 89 | # 'django.contrib.staticfiles.finders.DefaultStorageFinder', 90 | 'djangobower.finders.BowerFinder', 91 | ) 92 | 93 | # Make this unique, and don't share it with anybody. 94 | SECRET_KEY = 'sq)9^f#mf444c(#om$zpo0v!%y=%pqem*9s_qav93fwr_&x40u' 95 | 96 | # List of callables that know how to import templates from various sources. 97 | TEMPLATES = [{ 98 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 99 | 'DIRS': [os.path.join(APPLICATION_DIR, 'templates')], 100 | 'OPTIONS': { 101 | 'debug': DEBUG, 102 | 'loaders': [ 103 | ('django.template.loaders.cached.Loader', [ 104 | 'django.template.loaders.filesystem.Loader', 105 | 'django.template.loaders.app_directories.Loader', 106 | 'admin_tools.template_loaders.Loader', 107 | ]), 108 | ], 109 | 'context_processors': [ 110 | "django.contrib.auth.context_processors.auth", 111 | "django.contrib.messages.context_processors.messages", 112 | "django.template.context_processors.debug", 113 | "django.template.context_processors.i18n", 114 | "django.template.context_processors.media", 115 | "django.template.context_processors.static", 116 | "django.template.context_processors.csrf", 117 | "django.template.context_processors.tz", 118 | "django.template.context_processors.request", 119 | ] 120 | }, 121 | }] 122 | 123 | # for Django < 1.8 124 | TEMPLATE_LOADERS = ( 125 | 'django.template.loaders.filesystem.Loader', 126 | 'django.template.loaders.app_directories.Loader', 127 | 'admin_tools.template_loaders.Loader', 128 | ) 129 | TEMPLATE_CONTEXT_PROCESSORS = ( 130 | "django.contrib.auth.context_processors.auth", 131 | "django.core.context_processors.debug", 132 | "django.core.context_processors.i18n", 133 | "django.core.context_processors.media", 134 | "django.core.context_processors.static", 135 | "django.core.context_processors.csrf", 136 | "django.core.context_processors.tz", 137 | "django.core.context_processors.request", 138 | ) 139 | 140 | 141 | MIDDLEWARE_CLASSES = ( 142 | 'django.middleware.common.CommonMiddleware', 143 | 'django.contrib.sessions.middleware.SessionMiddleware', 144 | 'django.middleware.csrf.CsrfViewMiddleware', 145 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 146 | 'django.contrib.messages.middleware.MessageMiddleware', 147 | # Uncomment the next line for simple clickjacking protection: 148 | # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 149 | ) 150 | MIDDLEWARE = MIDDLEWARE_CLASSES 151 | 152 | 153 | ROOT_URLCONF = 'demoproject.urls' 154 | 155 | # Python dotted path to the WSGI application used by Django's runserver. 156 | WSGI_APPLICATION = 'demoproject.wsgi.application' 157 | 158 | INSTALLED_APPS = ( 159 | #admin tool apps 160 | 'admin_tools', 161 | 'admin_tools.theming', 162 | 'admin_tools.menu', 163 | 'admin_tools.dashboard', 164 | 'django.contrib.admin', 165 | 'django.contrib.auth', 166 | 'django.contrib.contenttypes', 167 | 'django.contrib.sessions', 168 | 'django.contrib.sites', 169 | 'django.contrib.messages', 170 | 'django.contrib.staticfiles', 171 | 'django_nvd3', 172 | 'djangobower', 173 | 'demoproject', 174 | 'admin_tools_stats', 175 | # 'south', 176 | ) 177 | 178 | # Django extensions 179 | try: 180 | import django_extensions 181 | except ImportError: 182 | pass 183 | else: 184 | INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) 185 | 186 | # A sample logging configuration. The only tangible logging 187 | # performed by this configuration is to send an email to 188 | # the site admins on every HTTP 500 error when DEBUG=False. 189 | # See http://docs.djangoproject.com/en/dev/topics/logging for 190 | # more details on how to customize your logging configuration. 191 | LOGGING = { 192 | 'version': 1, 193 | 'disable_existing_loggers': False, 194 | 'filters': { 195 | 'require_debug_false': { 196 | '()': 'django.utils.log.RequireDebugFalse' 197 | } 198 | }, 199 | 'handlers': { 200 | 'mail_admins': { 201 | 'level': 'ERROR', 202 | 'filters': ['require_debug_false'], 203 | 'class': 'django.utils.log.AdminEmailHandler' 204 | } 205 | }, 206 | 'loggers': { 207 | 'django.request': { 208 | 'handlers': ['mail_admins'], 209 | 'level': 'ERROR', 210 | 'propagate': True, 211 | }, 212 | } 213 | } 214 | 215 | 216 | # Django-bower 217 | # ------------ 218 | 219 | # Specifie path to components root (you need to use absolute path) 220 | BOWER_COMPONENTS_ROOT = os.path.join(PROJECT_ROOT, 'components') 221 | 222 | BOWER_PATH = '/usr/local/bin/bower' 223 | 224 | BOWER_INSTALLED_APPS = ( 225 | 'jquery#2.0.3', 226 | 'jquery-ui#~1.10.3', 227 | 'd3#3.3.6', 228 | 'nvd3#1.1.12-beta', 229 | ) 230 | 231 | #DJANGO-ADMIN-TOOL 232 | #================= 233 | ADMIN_TOOLS_MENU = 'menu.CustomMenu' 234 | ADMIN_TOOLS_INDEX_DASHBOARD = 'dashboard.CustomIndexDashboard' 235 | ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'dashboard.CustomAppIndexDashboard' 236 | ADMIN_MEDIA_PREFIX = '/static/admin/' 237 | 238 | # Django extensions 239 | try: 240 | import django_extensions 241 | except ImportError: 242 | pass 243 | else: 244 | INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) 245 | 246 | 247 | #IMPORT LOCAL SETTINGS 248 | #===================== 249 | try: 250 | from settings_local import * 251 | except ImportError: 252 | pass 253 | -------------------------------------------------------------------------------- /admin_tools_stats/modules.py: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # This Source Code Form is subject to the terms of the Mozilla Public 4 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 | # You can obtain one at http://mozilla.org/MPL/2.0/. 6 | # 7 | # Copyright (C) 2011-2014 Star2Billing S.L. 8 | # 9 | # The Initial Developer of the Original Code is 10 | # Arezqui Belaid 11 | # 12 | from django.db.models.aggregates import Count, Sum, Avg, Max, Min, StdDev, Variance 13 | from django.contrib.auth import get_user_model 14 | from django.utils.translation import ugettext_lazy as _ 15 | from django.apps import apps 16 | try: # Python 3 17 | from django.utils.encoding import force_text 18 | except ImportError: # Python 2 19 | from django.utils.encoding import force_unicode as force_text 20 | from django.contrib import messages 21 | from django.core.exceptions import FieldError 22 | from django.utils.safestring import mark_safe 23 | from qsstats import QuerySetStats 24 | from cache_utils.decorators import cached 25 | from admin_tools.dashboard import modules 26 | from admin_tools_stats.models import DashboardStats 27 | from datetime import datetime, timedelta 28 | 29 | import time 30 | 31 | from django.utils.timezone import now 32 | 33 | 34 | class DashboardChart(modules.DashboardModule): 35 | """Dashboard module with user registration charts. 36 | 37 | Default values are best suited for 2-column dashboard layouts. 38 | """ 39 | title = _('dashboard stats').title() 40 | template = 'admin_tools_stats/modules/chart.html' 41 | days = None 42 | interval = 'days' 43 | tooltip_date_format = "%d %b %Y" 44 | interval_dateformat_map = { 45 | 'months': ("%b", "%b"), 46 | 'days': ("%d %b %Y", "%a"), 47 | 'hours': ("%d %b %Y %H:%S", "%H"), 48 | } 49 | chart_type = 'discreteBarChart' 50 | chart_height = 300 51 | chart_width = '100%' 52 | require_chart_jscss = False 53 | extra = dict() 54 | 55 | model = None 56 | graph_key = None 57 | filter_list = None 58 | chart_container = None 59 | 60 | def is_empty(self): 61 | return False 62 | 63 | def get_day_intervals(self): 64 | return {'hours': 24, 'days': 7, 'weeks': 7 * 1, 'months': 30 * 2}[self.interval] 65 | 66 | def __init__(self, *args, **kwargs): 67 | super(DashboardChart, self).__init__(*args, **kwargs) 68 | self.select_box_value = '' 69 | self.other_select_box_values = {} 70 | self.require_chart_jscss = kwargs['require_chart_jscss'] 71 | self.graph_key = kwargs['graph_key'] 72 | for key in kwargs: 73 | if key.startswith('select_box_'): 74 | if key == 'select_box_' + self.graph_key: 75 | self.select_box_value = kwargs[key] 76 | else: 77 | self.other_select_box_values[key] = kwargs[key] 78 | 79 | if self.days is None: 80 | self.days = self.get_day_intervals() 81 | 82 | def init_with_context(self, context): 83 | super(DashboardChart, self).init_with_context(context) 84 | request = context['request'] 85 | 86 | self.data = self.get_registrations(request.user, self.interval, self.days, 87 | self.graph_key, self.select_box_value) 88 | self.prepare_template_data(self.data, self.graph_key, self.select_box_value, self.other_select_box_values) 89 | 90 | if hasattr(self, 'error_message'): 91 | messages.add_message(request, messages.ERROR, "%s dashboard: %s" % (self.title, self.error_message)) 92 | 93 | @cached(60 * 5) 94 | def get_registrations(self, user, interval, days, graph_key, select_box_value): 95 | """ Returns an array with new users count per interval.""" 96 | try: 97 | conf_data = DashboardStats.objects.get(graph_key=graph_key) 98 | model_name = apps.get_model(conf_data.model_app_name, conf_data.model_name) 99 | kwargs = {} 100 | if not user.is_superuser and conf_data.user_field_name: 101 | kwargs[conf_data.user_field_name] = user 102 | for i in conf_data.criteria.all(): 103 | # fixed mapping value passed info kwargs 104 | if i.criteria_fix_mapping: 105 | for key in i.criteria_fix_mapping: 106 | # value => i.criteria_fix_mapping[key] 107 | kwargs[key] = i.criteria_fix_mapping[key] 108 | 109 | # dynamic mapping value passed info kwargs 110 | if i.dynamic_criteria_field_name and select_box_value: 111 | kwargs[i.dynamic_criteria_field_name] = select_box_value 112 | 113 | aggregate = None 114 | if conf_data.type_operation_field_name and conf_data.operation_field_name: 115 | operation = { 116 | 'DistinctCount': Count(conf_data.operation_field_name, distinct=True), 117 | 'Count': Count(conf_data.operation_field_name), 118 | 'Sum': Sum(conf_data.operation_field_name), 119 | 'Avg': Avg(conf_data.operation_field_name), 120 | 'StdDev': StdDev(conf_data.operation_field_name), 121 | 'Max': Max(conf_data.operation_field_name), 122 | 'Min': Min(conf_data.operation_field_name), 123 | 'Variance': Variance(conf_data.operation_field_name), 124 | } 125 | aggregate = operation[conf_data.type_operation_field_name] 126 | 127 | stats = QuerySetStats(model_name.objects.filter(**kwargs).distinct(), 128 | conf_data.date_field_name, aggregate) 129 | # stats = QuerySetStats(User.objects.filter(is_active=True), 'date_joined') 130 | today = now() 131 | if days == 24: 132 | begin = today - timedelta(hours=days - 1) 133 | return stats.time_series(begin, today + timedelta(hours=1), interval) 134 | 135 | begin = today - timedelta(days=days - 1) 136 | return stats.time_series(begin, today + timedelta(days=1), interval) 137 | except (LookupError, FieldError, TypeError) as e: 138 | self.error_message = str(e) 139 | User = get_user_model() 140 | stats = QuerySetStats( 141 | User.objects.filter(is_active=True), 'date_joined') 142 | today = now() 143 | if days == 24: 144 | begin = today - timedelta(hours=days - 1) 145 | return stats.time_series(begin, today + timedelta(hours=1), interval) 146 | begin = today - timedelta(days=days - 1) 147 | return stats.time_series(begin, today + timedelta(days=1), interval) 148 | 149 | @cached(60 * 5) 150 | def prepare_template_data(self, data, graph_key, select_box_value, other_select_box_values): 151 | """ Prepares data for template (passed as module attributes) """ 152 | self.extra = { 153 | 'x_is_date': True, 154 | 'tag_script_js': False, 155 | 'jquery_on_ready': False, 156 | } 157 | 158 | if self.interval in self.interval_dateformat_map: 159 | self.tooltip_date_format, self.extra['x_axis_format'] = self.interval_dateformat_map[self.interval] 160 | 161 | self.chart_container = self.interval + '_' + self.graph_key 162 | # add string into href attr 163 | self.id = self.chart_container 164 | 165 | xdata = [] 166 | ydata = [] 167 | for data_date in self.data: 168 | start_time = int(time.mktime(data_date[0].timetuple()) * 1000) 169 | xdata.append(start_time) 170 | ydata.append(data_date[1]) 171 | 172 | extra_serie = {"tooltip": {"y_start": "", "y_end": ""}, 173 | "date_format": self.tooltip_date_format} 174 | 175 | self.values = { 176 | 'x': xdata, 177 | 'name1': self.interval, 'y1': ydata, 'extra1': extra_serie, 178 | } 179 | 180 | self.form_field = get_dynamic_criteria(graph_key, select_box_value, other_select_box_values) 181 | 182 | 183 | @cached(60 * 5) 184 | def get_title(graph_key): 185 | """Returns graph title""" 186 | try: 187 | return DashboardStats.objects.get(graph_key=graph_key).graph_title 188 | except LookupError as e: 189 | self.error_message = str(e) 190 | return '' 191 | 192 | 193 | @cached(60 * 5) 194 | def get_dynamic_criteria(graph_key, select_box_value, other_select_box_values): 195 | """To get dynamic criteria & return into select box to display on dashboard""" 196 | try: 197 | temp = '' 198 | conf_data = DashboardStats.objects.get(graph_key=graph_key).criteria.all() 199 | for i in conf_data: 200 | dy_map = i.criteria_dynamic_mapping 201 | if dy_map: 202 | temp = '' 210 | 211 | temp += "\n".join(['' % (key, other_select_box_values[key]) for key in other_select_box_values ]) 212 | 213 | return mark_safe(force_text(temp)) 214 | except LookupError as e: 215 | self.error_message = str(e) 216 | return '' 217 | 218 | 219 | def get_active_graph(): 220 | """Returns active graphs""" 221 | try: 222 | return DashboardStats.objects.filter(is_visible=1) 223 | except LookupError as e: 224 | self.error_message = str(e) 225 | return [] 226 | 227 | 228 | class DashboardCharts(modules.Group): 229 | """Group module with 3 default dashboard charts""" 230 | title = _('new users') 231 | 232 | def get_registration_charts(self, **kwargs): 233 | """ Returns 3 basic chart modules (today, last 7 days & last 3 months) """ 234 | return [ 235 | DashboardChart(_('today').title(), interval='hours', **kwargs), 236 | DashboardChart(_('last week').title(), interval='days', **kwargs), 237 | DashboardChart(_('last 2 weeks'), interval='weeks', **kwargs), 238 | DashboardChart(_('last 3 months').title(), interval='months', **kwargs), 239 | ] 240 | 241 | def __init__(self, *args, **kwargs): 242 | key_value = kwargs.get('graph_key') 243 | self.title = get_title(key_value) 244 | kwargs.setdefault('children', self.get_registration_charts(**kwargs)) 245 | super(DashboardCharts, self).__init__(*args, **kwargs) 246 | --------------------------------------------------------------------------------