├── .gitignore ├── README.md ├── core ├── __init__.py ├── admin.py ├── apps.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── requirements.txt ├── shop ├── __init__.py ├── admin.py ├── apps.py ├── management │ └── commands │ │ └── populate_db.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── templates │ ├── admin │ │ ├── shop │ │ │ └── app_index.html │ │ └── statistics.html │ └── statistics.html ├── tests.py ├── urls.py └── views.py └── utils └── charts.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/pycharm+all,django 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=pycharm+all,django 3 | 4 | ### Django ### 5 | *.log 6 | *.pot 7 | *.pyc 8 | __pycache__/ 9 | local_settings.py 10 | db.sqlite3 11 | db.sqlite3-journal 12 | media 13 | 14 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 15 | # in your Git repository. Update and uncomment the following line accordingly. 16 | # /staticfiles/ 17 | 18 | ### Django.Python Stack ### 19 | # Byte-compiled / optimized / DLL files 20 | *.py[cod] 21 | *$py.class 22 | 23 | # C extensions 24 | *.so 25 | 26 | # Distribution / packaging 27 | .Python 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | wheels/ 40 | pip-wheel-metadata/ 41 | share/python-wheels/ 42 | *.egg-info/ 43 | .installed.cfg 44 | *.egg 45 | MANIFEST 46 | 47 | # PyInstaller 48 | # Usually these files are written by a python script from a template 49 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 50 | *.manifest 51 | *.spec 52 | 53 | # Installer logs 54 | pip-log.txt 55 | pip-delete-this-directory.txt 56 | 57 | # Unit test / coverage reports 58 | htmlcov/ 59 | .tox/ 60 | .nox/ 61 | .coverage 62 | .coverage.* 63 | .cache 64 | nosetests.xml 65 | coverage.xml 66 | *.cover 67 | *.py,cover 68 | .hypothesis/ 69 | .pytest_cache/ 70 | pytestdebug.log 71 | 72 | # Translations 73 | *.mo 74 | 75 | # Django stuff: 76 | 77 | # Flask stuff: 78 | instance/ 79 | .webassets-cache 80 | 81 | # Scrapy stuff: 82 | .scrapy 83 | 84 | # Sphinx documentation 85 | docs/_build/ 86 | doc/_build/ 87 | 88 | # PyBuilder 89 | target/ 90 | 91 | # Jupyter Notebook 92 | .ipynb_checkpoints 93 | 94 | # IPython 95 | profile_default/ 96 | ipython_config.py 97 | 98 | # pyenv 99 | .python-version 100 | 101 | # pipenv 102 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 103 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 104 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 105 | # install all needed dependencies. 106 | #Pipfile.lock 107 | 108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 109 | __pypackages__/ 110 | 111 | # Celery stuff 112 | celerybeat-schedule 113 | celerybeat.pid 114 | 115 | # SageMath parsed files 116 | *.sage.py 117 | 118 | # Environments 119 | .env 120 | .venv 121 | env/ 122 | venv/ 123 | ENV/ 124 | env.bak/ 125 | venv.bak/ 126 | pythonenv* 127 | 128 | # Spyder project settings 129 | .spyderproject 130 | .spyproject 131 | 132 | # Rope project settings 133 | .ropeproject 134 | 135 | # mkdocs documentation 136 | /site 137 | 138 | # mypy 139 | .mypy_cache/ 140 | .dmypy.json 141 | dmypy.json 142 | 143 | # Pyre type checker 144 | .pyre/ 145 | 146 | # pytype static type analyzer 147 | .pytype/ 148 | 149 | # profiling data 150 | .prof 151 | 152 | ### PyCharm+all ### 153 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 154 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 155 | 156 | # User-specific stuff 157 | .idea/**/workspace.xml 158 | .idea/**/tasks.xml 159 | .idea/**/usage.statistics.xml 160 | .idea/**/dictionaries 161 | .idea/**/shelf 162 | 163 | # Generated files 164 | .idea/**/contentModel.xml 165 | 166 | # Sensitive or high-churn files 167 | .idea/**/dataSources/ 168 | .idea/**/dataSources.ids 169 | .idea/**/dataSources.local.xml 170 | .idea/**/sqlDataSources.xml 171 | .idea/**/dynamic.xml 172 | .idea/**/uiDesigner.xml 173 | .idea/**/dbnavigator.xml 174 | 175 | # Gradle 176 | .idea/**/gradle.xml 177 | .idea/**/libraries 178 | 179 | # Gradle and Maven with auto-import 180 | # When using Gradle or Maven with auto-import, you should exclude module files, 181 | # since they will be recreated, and may cause churn. Uncomment if using 182 | # auto-import. 183 | # .idea/artifacts 184 | # .idea/compiler.xml 185 | # .idea/jarRepositories.xml 186 | # .idea/modules.xml 187 | # .idea/*.iml 188 | # .idea/modules 189 | # *.iml 190 | # *.ipr 191 | 192 | # CMake 193 | cmake-build-*/ 194 | 195 | # Mongo Explorer plugin 196 | .idea/**/mongoSettings.xml 197 | 198 | # File-based project format 199 | *.iws 200 | 201 | # IntelliJ 202 | out/ 203 | 204 | # mpeltonen/sbt-idea plugin 205 | .idea_modules/ 206 | 207 | # JIRA plugin 208 | atlassian-ide-plugin.xml 209 | 210 | # Cursive Clojure plugin 211 | .idea/replstate.xml 212 | 213 | # Crashlytics plugin (for Android Studio and IntelliJ) 214 | com_crashlytics_export_strings.xml 215 | crashlytics.properties 216 | crashlytics-build.properties 217 | fabric.properties 218 | 219 | # Editor-based Rest Client 220 | .idea/httpRequests 221 | 222 | # Android studio 3.1+ serialized cache file 223 | .idea/caches/build_file_checksums.ser 224 | 225 | ### PyCharm+all Patch ### 226 | # Ignores the whole .idea folder and all .iml files 227 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 228 | 229 | .idea/ 230 | 231 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 232 | 233 | *.iml 234 | modules.xml 235 | .idea/misc.xml 236 | *.ipr 237 | 238 | # Sonarlint plugin 239 | .idea/sonarlint 240 | 241 | # End of https://www.toptal.com/developers/gitignore/api/pycharm+all,django -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Interactive Charts 2 | 3 | ## Want to learn how to build this? 4 | 5 | Check out the [post](https://testdriven.io/blog/django-charts/). 6 | 7 | ## Want to use this project? 8 | 9 | 1. Fork/Clone 10 | 11 | 1. Create and activate a virtual environment: 12 | 13 | ```sh 14 | $ python3 -m venv venv && source venv/bin/activate 15 | ``` 16 | 17 | 1. Install the requirements: 18 | 19 | ```sh 20 | (venv)$ pip install -r requirements.txt 21 | ``` 22 | 23 | 1. Apply the migrations: 24 | 25 | ```sh 26 | (venv)$ python manage.py migrate 27 | ``` 28 | 29 | 1. Populate the database with randomly generated data (amount = number of purchases): 30 | 31 | ```sh 32 | (venv)$ python manage.py populate_db --amount 2500 33 | ``` 34 | 35 | 1. Create a superuser, and run the server: 36 | 37 | ```sh 38 | (venv)$ python manage.py createsuperuser 39 | (venv)$ python manage.py runserver 40 | ``` 41 | 42 | 1. You can then see the charts here: 43 | 44 | - [http://127.0.0.1:8000/shop/statistics/](http://127.0.0.1:8000/shop/statistics/) - stats view 45 | - [http://127.0.0.1:8000/admin/statistics/](http://127.0.0.1:8000/admin/statistics/) - new admin view 46 | - [http://127.0.0.1:8000/admin/shop/](http://127.0.0.1:8000/admin/shop/) - extended admin view 47 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-interactive-charts/7ad50f65608a288f051b28dbd5f782383f1c4fbd/core/__init__.py -------------------------------------------------------------------------------- /core/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.admin.views.decorators import staff_member_required 3 | from django.shortcuts import render 4 | from django.urls import path 5 | 6 | 7 | @staff_member_required 8 | def admin_statistics_view(request): 9 | return render(request, "admin/statistics.html", { 10 | "title": "Statistics" 11 | }) 12 | 13 | 14 | class CustomAdminSite(admin.AdminSite): 15 | def get_app_list(self, request, _=None): 16 | app_list = super().get_app_list(request) 17 | app_list += [ 18 | { 19 | "name": "My Custom App", 20 | "app_label": "my_custom_app", 21 | "models": [ 22 | { 23 | "name": "Statistics", 24 | "object_name": "statistics", 25 | "admin_url": "/admin/statistics", 26 | "view_only": True, 27 | } 28 | ], 29 | } 30 | ] 31 | return app_list 32 | 33 | def get_urls(self): 34 | urls = super().get_urls() 35 | urls += [ 36 | path("statistics/", admin_statistics_view, name="admin-statistics"), 37 | ] 38 | return urls 39 | -------------------------------------------------------------------------------- /core/apps.py: -------------------------------------------------------------------------------- 1 | from django.contrib.admin.apps import AdminConfig 2 | 3 | 4 | class CustomAdminConfig(AdminConfig): 5 | default_site = "core.admin.CustomAdminSite" 6 | -------------------------------------------------------------------------------- /core/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for core project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /core/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for core project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = "django-insecure-(75wtsp_$sbh8ekihexk)hpt5cc_a9l9ovuv36o+3v0v(w6wfm" 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | "core.apps.CustomAdminConfig", 35 | "django.contrib.auth", 36 | "django.contrib.contenttypes", 37 | "django.contrib.sessions", 38 | "django.contrib.messages", 39 | "django.contrib.staticfiles", 40 | "shop.apps.ShopConfig", 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | "django.middleware.security.SecurityMiddleware", 45 | "django.contrib.sessions.middleware.SessionMiddleware", 46 | "django.middleware.common.CommonMiddleware", 47 | "django.middleware.csrf.CsrfViewMiddleware", 48 | "django.contrib.auth.middleware.AuthenticationMiddleware", 49 | "django.contrib.messages.middleware.MessageMiddleware", 50 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 51 | ] 52 | 53 | ROOT_URLCONF = "core.urls" 54 | 55 | TEMPLATES = [ 56 | { 57 | "BACKEND": "django.template.backends.django.DjangoTemplates", 58 | "DIRS": [], 59 | "APP_DIRS": True, 60 | "OPTIONS": { 61 | "context_processors": [ 62 | "django.template.context_processors.debug", 63 | "django.template.context_processors.request", 64 | "django.contrib.auth.context_processors.auth", 65 | "django.contrib.messages.context_processors.messages", 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = "core.wsgi.application" 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/4.2/ref/settings/#databases 76 | 77 | DATABASES = { 78 | "default": { 79 | "ENGINE": "django.db.backends.sqlite3", 80 | "NAME": BASE_DIR / "db.sqlite3", 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", 91 | }, 92 | { 93 | "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", 94 | }, 95 | { 96 | "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", 97 | }, 98 | { 99 | "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/4.2/topics/i18n/ 106 | 107 | LANGUAGE_CODE = "en-us" 108 | 109 | TIME_ZONE = "UTC" 110 | 111 | USE_I18N = True 112 | 113 | USE_TZ = True 114 | 115 | 116 | # Static files (CSS, JavaScript, Images) 117 | # https://docs.djangoproject.com/en/4.2/howto/static-files/ 118 | 119 | STATIC_URL = "static/" 120 | 121 | # Default primary key field type 122 | # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field 123 | 124 | DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" 125 | -------------------------------------------------------------------------------- /core/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path, include 3 | 4 | from .admin import admin_statistics_view 5 | 6 | urlpatterns = [ 7 | path( 8 | "admin/statistics/", 9 | admin.site.admin_view(admin_statistics_view), 10 | name="admin-statistics" 11 | ), 12 | path("admin/", admin.site.urls), 13 | path("shop/", include("shop.urls")), 14 | ] 15 | -------------------------------------------------------------------------------- /core/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for core project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django==4.2 2 | pytz==2023.3 -------------------------------------------------------------------------------- /shop/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-interactive-charts/7ad50f65608a288f051b28dbd5f782383f1c4fbd/shop/__init__.py -------------------------------------------------------------------------------- /shop/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from shop.models import Item, Purchase 4 | 5 | 6 | admin.site.register(Item) 7 | admin.site.register(Purchase) 8 | -------------------------------------------------------------------------------- /shop/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ShopConfig(AppConfig): 5 | default_auto_field = "django.db.models.BigAutoField" 6 | name = "shop" 7 | -------------------------------------------------------------------------------- /shop/management/commands/populate_db.py: -------------------------------------------------------------------------------- 1 | import random 2 | from datetime import datetime, timedelta 3 | 4 | import pytz 5 | from django.core.management.base import BaseCommand 6 | 7 | from shop.models import Item, Purchase 8 | 9 | 10 | class Command(BaseCommand): 11 | help = "Populates the database with random generated data." 12 | 13 | def add_arguments(self, parser): 14 | parser.add_argument("--amount", type=int, help="The number of purchases that should be created.") 15 | 16 | def handle(self, *args, **options): 17 | names = ["James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Thomas", "Charles"] 18 | surname = ["Smith", "Jones", "Taylor", "Brown", "Williams", "Wilson", "Johnson", "Davies", "Patel", "Wright"] 19 | items = [ 20 | Item.objects.get_or_create(name="Socks", price=6.5), Item.objects.get_or_create(name="Pants", price=12), 21 | Item.objects.get_or_create(name="T-Shirt", price=8), Item.objects.get_or_create(name="Boots", price=9), 22 | Item.objects.get_or_create(name="Sweater", price=3), Item.objects.get_or_create(name="Underwear", price=9), 23 | Item.objects.get_or_create(name="Leggings", price=7), Item.objects.get_or_create(name="Cap", price=5), 24 | ] 25 | amount = options["amount"] if options["amount"] else 2500 26 | for i in range(0, amount): 27 | dt = pytz.utc.localize(datetime.now() - timedelta(days=random.randint(0, 1825))) 28 | purchase = Purchase.objects.create( 29 | customer_full_name=random.choice(names) + " " + random.choice(surname), 30 | item=random.choice(items)[0], 31 | payment_method=random.choice(Purchase.PAYMENT_METHODS)[0], 32 | successful=True if random.randint(1, 2) == 1 else False, 33 | ) 34 | purchase.time = dt 35 | purchase.save() 36 | 37 | self.stdout.write(self.style.SUCCESS("Successfully populated the database.")) 38 | -------------------------------------------------------------------------------- /shop/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.2 on 2023-04-15 14:53 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name="Item", 16 | fields=[ 17 | ( 18 | "id", 19 | models.BigAutoField( 20 | auto_created=True, 21 | primary_key=True, 22 | serialize=False, 23 | verbose_name="ID", 24 | ), 25 | ), 26 | ("name", models.CharField(max_length=255)), 27 | ("description", models.TextField(null=True)), 28 | ("price", models.FloatField(default=0)), 29 | ], 30 | ), 31 | migrations.CreateModel( 32 | name="Purchase", 33 | fields=[ 34 | ( 35 | "id", 36 | models.BigAutoField( 37 | auto_created=True, 38 | primary_key=True, 39 | serialize=False, 40 | verbose_name="ID", 41 | ), 42 | ), 43 | ("customer_full_name", models.CharField(max_length=64)), 44 | ( 45 | "payment_method", 46 | models.CharField( 47 | choices=[ 48 | ("CC", "Credit card"), 49 | ("DC", "Debit card"), 50 | ("ET", "Ethereum"), 51 | ("BC", "Bitcoin"), 52 | ], 53 | default="CC", 54 | max_length=2, 55 | ), 56 | ), 57 | ("time", models.DateTimeField(auto_now_add=True)), 58 | ("successful", models.BooleanField(default=False)), 59 | ( 60 | "item", 61 | models.ForeignKey( 62 | on_delete=django.db.models.deletion.CASCADE, to="shop.item" 63 | ), 64 | ), 65 | ], 66 | options={ 67 | "ordering": ["-time"], 68 | }, 69 | ), 70 | ] 71 | -------------------------------------------------------------------------------- /shop/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duplxey/django-interactive-charts/7ad50f65608a288f051b28dbd5f782383f1c4fbd/shop/migrations/__init__.py -------------------------------------------------------------------------------- /shop/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Item(models.Model): 5 | name = models.CharField(max_length=255) 6 | description = models.TextField(null=True) 7 | price = models.FloatField(default=0) 8 | 9 | def __str__(self): 10 | return f"{self.name} (${self.price})" 11 | 12 | 13 | class Purchase(models.Model): 14 | customer_full_name = models.CharField(max_length=64) 15 | item = models.ForeignKey(to=Item, on_delete=models.CASCADE) 16 | PAYMENT_METHODS = [ 17 | ("CC", "Credit card"), 18 | ("DC", "Debit card"), 19 | ("ET", "Ethereum"), 20 | ("BC", "Bitcoin"), 21 | ] 22 | payment_method = models.CharField(max_length=2, default="CC", choices=PAYMENT_METHODS) 23 | time = models.DateTimeField(auto_now_add=True) 24 | successful = models.BooleanField(default=False) 25 | 26 | class Meta: 27 | ordering = ["-time"] 28 | 29 | def __str__(self): 30 | return f"{self.customer_full_name}, {self.payment_method} ({self.item.name})" 31 | -------------------------------------------------------------------------------- /shop/templates/admin/shop/app_index.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/index.html" %} 2 | {% load i18n %} 3 | {% block bodyclass %}{{ block.super }} app-{{ app_label }}{% endblock %} 4 | {% if not is_popup %} 5 | {% block breadcrumbs %} 6 | 13 | {% endblock %} 14 | {% endif %} 15 | {% block content %} 16 |
17 |
18 | {% include "admin/app_list.html" with app_list=app_list show_changelinks=True %} 19 |
20 |
21 |

Statistics

22 | 23 | 28 |
29 | 30 | 31 | 32 |
33 | 93 | 94 | 95 | 96 | 97 | 159 |
160 |
161 | {% endblock %} 162 | -------------------------------------------------------------------------------- /shop/templates/admin/statistics.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/base_site.html" %} 2 | {% block content %} 3 | 4 | 9 | 10 |
11 | 12 | 13 | 14 |
15 | 75 |
76 |
77 | 78 |
79 |
80 | 81 |
82 |
83 | 84 |
85 |
86 | 87 |
88 |
89 | 155 | {% endblock %} 156 | -------------------------------------------------------------------------------- /shop/templates/statistics.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Statistics 5 | 6 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | 18 | 19 |
20 |
21 |
22 | 23 |
24 |
25 | 26 |
27 |
28 | 29 |
30 |
31 | 32 |
33 |
34 | 94 | 160 |
161 | 162 | 163 | -------------------------------------------------------------------------------- /shop/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /shop/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path("statistics/", views.statistics_view, name="shop-statistics"), 7 | path("chart/filter-options/", views.get_filter_options, name="chart-filter-options"), 8 | path("chart/sales//", views.get_sales_chart, name="chart-sales"), 9 | path("chart/spend-per-customer//", views.spend_per_customer_chart, name="chart-spend-per-customer"), 10 | path("chart/payment-success//", views.payment_success_chart, name="chart-payment-success"), 11 | path("chart/payment-method//", views.payment_method_chart, name="chart-payment-method"), 12 | ] 13 | -------------------------------------------------------------------------------- /shop/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.admin.views.decorators import staff_member_required 2 | from django.db.models import Count, F, Sum, Avg 3 | from django.db.models.functions import ExtractYear, ExtractMonth 4 | from django.http import JsonResponse 5 | from django.shortcuts import render 6 | 7 | from shop.models import Purchase 8 | from utils.charts import months, colorPrimary, colorSuccess, colorDanger, generate_color_palette, get_year_dict 9 | 10 | 11 | @staff_member_required 12 | def get_filter_options(request): 13 | grouped_purchases = Purchase.objects.annotate(year=ExtractYear("time")).values("year").order_by("-year").distinct() 14 | options = [purchase["year"] for purchase in grouped_purchases] 15 | 16 | return JsonResponse({ 17 | "options": options, 18 | }) 19 | 20 | 21 | @staff_member_required 22 | def get_sales_chart(request, year): 23 | purchases = Purchase.objects.filter(time__year=year) 24 | grouped_purchases = purchases.annotate(price=F("item__price")).annotate(month=ExtractMonth("time"))\ 25 | .values("month").annotate(average=Sum("item__price")).values("month", "average").order_by("month") 26 | 27 | sales_dict = get_year_dict() 28 | 29 | for group in grouped_purchases: 30 | sales_dict[months[group["month"]-1]] = round(group["average"], 2) 31 | 32 | return JsonResponse({ 33 | "title": f"Sales in {year}", 34 | "data": { 35 | "labels": list(sales_dict.keys()), 36 | "datasets": [{ 37 | "label": "Amount ($)", 38 | "backgroundColor": colorPrimary, 39 | "borderColor": colorPrimary, 40 | "data": list(sales_dict.values()), 41 | }] 42 | }, 43 | }) 44 | 45 | 46 | @staff_member_required 47 | def spend_per_customer_chart(request, year): 48 | purchases = Purchase.objects.filter(time__year=year) 49 | grouped_purchases = purchases.annotate(price=F("item__price")).annotate(month=ExtractMonth("time"))\ 50 | .values("month").annotate(average=Avg("item__price")).values("month", "average").order_by("month") 51 | 52 | spend_per_customer_dict = get_year_dict() 53 | 54 | for group in grouped_purchases: 55 | spend_per_customer_dict[months[group["month"]-1]] = round(group["average"], 2) 56 | 57 | return JsonResponse({ 58 | "title": f"Spend per customer in {year}", 59 | "data": { 60 | "labels": list(spend_per_customer_dict.keys()), 61 | "datasets": [{ 62 | "label": "Amount ($)", 63 | "backgroundColor": colorPrimary, 64 | "borderColor": colorPrimary, 65 | "data": list(spend_per_customer_dict.values()), 66 | }] 67 | }, 68 | }) 69 | 70 | 71 | @staff_member_required 72 | def payment_success_chart(request, year): 73 | purchases = Purchase.objects.filter(time__year=year) 74 | 75 | return JsonResponse({ 76 | "title": f"Payment success rate in {year}", 77 | "data": { 78 | "labels": ["Successful", "Unsuccessful"], 79 | "datasets": [{ 80 | "label": "Amount ($)", 81 | "backgroundColor": [colorSuccess, colorDanger], 82 | "borderColor": [colorSuccess, colorDanger], 83 | "data": [ 84 | purchases.filter(successful=True).count(), 85 | purchases.filter(successful=False).count(), 86 | ], 87 | }] 88 | }, 89 | }) 90 | 91 | 92 | @staff_member_required 93 | def payment_method_chart(request, year): 94 | purchases = Purchase.objects.filter(time__year=year) 95 | grouped_purchases = purchases.values("payment_method").annotate(count=Count("id"))\ 96 | .values("payment_method", "count").order_by("payment_method") 97 | 98 | payment_method_dict = dict() 99 | 100 | for payment_method in Purchase.PAYMENT_METHODS: 101 | payment_method_dict[payment_method[1]] = 0 102 | 103 | for group in grouped_purchases: 104 | payment_method_dict[dict(Purchase.PAYMENT_METHODS)[group["payment_method"]]] = group["count"] 105 | 106 | return JsonResponse({ 107 | "title": f"Payment method rate in {year}", 108 | "data": { 109 | "labels": list(payment_method_dict.keys()), 110 | "datasets": [{ 111 | "label": "Amount ($)", 112 | "backgroundColor": generate_color_palette(len(payment_method_dict)), 113 | "borderColor": generate_color_palette(len(payment_method_dict)), 114 | "data": list(payment_method_dict.values()), 115 | }] 116 | }, 117 | }) 118 | 119 | 120 | @staff_member_required 121 | def statistics_view(request): 122 | return render(request, "statistics.html", {}) 123 | -------------------------------------------------------------------------------- /utils/charts.py: -------------------------------------------------------------------------------- 1 | months = [ 2 | "January", "February", "March", "April", 3 | "May", "June", "July", "August", 4 | "September", "October", "November", "December" 5 | ] 6 | colorPalette = ["#55efc4", "#81ecec", "#a29bfe", "#ffeaa7", "#fab1a0", "#ff7675", "#fd79a8"] 7 | colorPrimary, colorSuccess, colorDanger = "#79aec8", colorPalette[0], colorPalette[5] 8 | 9 | 10 | def get_year_dict(): 11 | year_dict = dict() 12 | 13 | for month in months: 14 | year_dict[month] = 0 15 | 16 | return year_dict 17 | 18 | 19 | def generate_color_palette(amount): 20 | palette = [] 21 | 22 | i = 0 23 | while i < len(colorPalette) and len(palette) < amount: 24 | palette.append(colorPalette[i]) 25 | i += 1 26 | if i == len(colorPalette) and len(palette) < amount: 27 | i = 0 28 | 29 | return palette 30 | --------------------------------------------------------------------------------