Sådan oprettes et analysedashboard i en Django-app

Hej folkens!

Python , datavisualisering og programmering er de emner, jeg er dybt dedikeret til. Derfor vil jeg gerne dele med dig mine ideer såvel som min entusiasme for at opdage nye måder at præsentere data på en meningsfuld måde.

Sagen, jeg skal dække, er ret almindelig: du har data på bagsiden af ​​din app og vil give den form på frontenden. Hvis en sådan situation lyder bekendt for dig, kan denne tutorial være praktisk.

Når du har gennemført den, har du en Django-drevet app med interaktive drejetabeller og diagrammer .

Forudsætninger

For selvsikker at gå gennem trinnene har du brug for en grundlæggende viden om Django-rammen og lidt kreativitet . ✨

For at følge med kan du downloade GitHub-prøven.

Her er en kort liste over værktøjer, vi skal bruge:

  • Python 3.7.4
  • Django
  • Virtualenv
  • Flexmonster pivottabel og diagrammer (JavaScript-bibliotek)
  • SQLite

Hvis du allerede har oprettet et Django-projekt og føler dig sikker på den grundlæggende strøm af oprettelse af apps, kan du springe direkte til afsnittet Forbinde data til Flexmonster , der forklarer, hvordan du tilføjer datavisualiseringskomponenter til det.

Lad os begynde!

Kom godt i gang med Django

Første ting først, lad os sørge for at du har installeret Django på din maskine. Tommelfingerreglen er at installere den i dit tidligere oprettede virtuelle miljø - et kraftfuldt værktøj til at isolere dine projekter fra hinanden.

Sørg også for, at du har aktiveret i et nyoprettet bibliotek. Åbn din konsol, og start et Django-projekt med denne kommando:

django-admin startproject analytics_project

Nu er der en ny mappe kaldet analytics_project. Lad os kontrollere, om vi gjorde alt rigtigt. Gå til analytics_projectog start serveren med en konsolkommando:

python manage.py runserver

Åbn //127.0.0.1:8000/i din browser. Hvis du ser denne fantastiske raket, så er alt i orden:

Opret derefter en ny app i dit projekt. Lad os hedde det dashboard:

python manage.py startapp dashboard

Her er et tip : Hvis du ikke er sikker på forskellen mellem begreberne apps og projekter i Django, skal du tage dig tid til at lære om det for at få et klart billede af, hvordan Django-projekter er organiseret.

Nu sker det. Nu ser vi en ny mappe inden for projektet. Den indeholder følgende filer:

__init__.py for at få Python til at behandle det som en pakke

admin.py - indstillinger for Django-admin-siderne

apps.py - indstillinger for appens konfigurationer

models.py - klasser, der konverteres til databasetabeller af Djangos ORM

tests.py - testklasser

views.py - funktioner og klasser, der definerer, hvordan dataene vises i skabelonerne

Derefter er det nødvendigt at registrere appen i projektet.

Gå til analytics_project/settings.pyog tilføj appens navn til INSTALLED_APPSlisten:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', ]

Nu er vores projekt opmærksom på appens eksistens.

Visninger

I den dashboard/views.pyopretter vi en funktion, der leder en bruger til de specifikke skabeloner, der er defineret i dashboard/templatesmappen. Visninger kan også indeholde klasser.

Sådan definerer vi det:

from django.http import JsonResponse from django.shortcuts import render from dashboard.models import Order from django.core import serializers def dashboard_with_pivot(request): return render(request, 'dashboard_with_pivot.html', {})

Når denne funktion er ringet op, gengives den dashboard_with_pivot.html- en skabelon, som vi snart definerer. Den indeholder pivottabellen og pivotkortkomponenterne.

Et par flere ord om denne funktion. Dens requestargument, en forekomst af HttpRequestObject, indeholder oplysninger om anmodningen, f.eks. Den anvendte HTTP-metode (GET eller POST). Metoden rendersøger efter HTML-skabeloner i et templatesbibliotek inde i appens bibliotek.

Vi har også brug for at oprette en hjælpemetode, der sender svaret med data til pivottabellen på appens frontend. Lad os kalde det pivot_data:

def pivot_data(request): dataset = Order.objects.all() data = serializers.serialize('json', dataset) return JsonResponse(data, safe=False)

Sandsynligvis fortæller din IDE dig, at den ikke kan finde en reference Orderi models.py. Intet problem - vi behandler det senere.

Skabeloner

Indtil videre drager vi fordel af Django-skabelonsystemet.

Lad os oprette en ny mappe templatesinde dashboardog oprette den første HTML-skabelon, der hedder dashboard_with_pivot.html. Det vil blive vist for brugeren efter anmodning. Her tilføjer vi også scripts og containere til datavisualiseringskomponenter:

  Dashboard with Flexmonster 

Kortlægning af visningsfunktioner til webadresser

For at kalde visningerne og vise gengivne HTML-skabeloner til brugeren skal vi kortlægge visningerne til de tilsvarende URL'er.

Her er et tip: et af Djangos URL-designprincipper siger om løs kobling, vi bør ikke lave URL'er med de samme navne som Python-funktioner.

Go to analytics_app/urls.py and add relevant configurations for the dashboard app at the project's level.

from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('dashboard.urls')), ] 

Now the URLs from the dashboard app can be accessed but only if they are prefixed by dashboard.

After, go to dashboard/urls.py (create this file if it doesn’t exist) and add a list of URL patterns that are mapped to the view functions:

from django.urls import path from . import views urlpatterns = [ path('', views.dashboard_with_pivot, name="dashboard_with_pivot"), path('data', views.pivot_data, name="pivot_data"), ]

Model

And, at last, we've gotten to data modeling. This is my favorite part.

As you might know, a data model is a conceptual representation of the data stored in a database.

Since the purpose of this tutorial is to show how to build interactive data visualization inside the app, we won’t be worrying much about the database choice. We’ll be using SQLite - a lightweight database that ships with the Django web development server.

But keep in mind that this database is not the appropriate choice for production development. With the Django ORM, you can use other databases that use the SQL language, such as PostgreSQL or MySQL.

For the sake of simplicity, our model will consist of one class. You can create more classes and define relationships between them, complex or simple ones.

Imagine we're designing a dashboard for the sales department. So, let's create an Order class and define its attributes in dashboard/models.py:

from django.db import models class Order(models.Model): product_category = models.CharField(max_length=20) payment_method = models.CharField(max_length=50) shipping_cost = models.CharField(max_length=50) unit_price = models.DecimalField(max_digits=5, decimal_places=2)

Working with a database

Now we need to create a database and populate it with records.

But how can we translate our model class into a database table?

This is where the concept of migration comes in handy. Migration is simply a file that describes which changes must be applied to the database. Every time we need to create a database based on the model described by Python classes, we use migration.

The data may come as Python objects, dictionaries, or lists. This time we'll represent the entities from the database using Python classes that are located in the models directory.

Create migration for the app with one command:

python manage.py makemigrations dashboard

Here we specified that the app should tell Django to apply migrations for the dashboard app's models.

After creating a migration file, apply migrations described in it and create a database:

python manage.py migrate dashboard

If you see a new file db.sqlite3 in the project's directory, we are ready to work with the database.

Let's create instances of our Order class. For this, we'll use the Django shell - it's similar to the Python shell but allows accessing the database and creating new entries.

So, start the Django shell:

python manage.py shell

And write the following code in the interactive console:

from dashboard.models import Order >>> o1 = Order( ... product_category="Books", ... payment_method="Credit Card", ... shipping_cost=39, ... unit_price=59 ... ) >>> o1.save()

Similarly, you can create and save as many objects as you need.

Connecting data to Flexmonster

And here's what I promised to explain.

Let's figure out how to pass the data from your model to the data visualization tool on the front end.

To make the back end and Flexmonster communicate, we can follow two different approaches:

  • Using the request-response cycle. We can use Python and the Django template engine to write JavaScript code directly in the template.
  • Using an async request (AJAX) that returns the data in JSON.

In my mind, the second one is the most convenient because of a number of reasons. First of all, Flexmonster understands JSON. To be precise, it can accept an array of JSON objects as input data. Another benefit of using async requests is the better page loading speed and more maintainable code.

Let's see how it works.

Go to the templates/dashboard_pivot.html.

Here we've created two div containers where the pivot grid and pivot charts will be rendered.

Within the ajax call, we make a request based on the URL contained in the data-URL property. Then we tell the ajax request that we expect a JSON object to be returned (defined by dataType).

Once the request is completed, the JSON response returned by our server is set to the data parameter, and the pivot table, filled with this data, is rendered.

The query result (the instance of JSONResponse) returns a string that contains an array object with extra meta information, so we should add a tiny function for data processing on the front end. It will extract only those nested objects we need and put them into a single array. This is because Flexmonster accepts an array of JSON objects without nested levels.

function processData(dataset) { var result = [] dataset = JSON.parse(dataset); dataset.forEach(item => result.push(item.fields)); return result; }

After processing the data, the component receives it in the right format and performs all the hard work of data visualization. A huge plus is that there’s no need to group or aggregate the values of objects manually.

Here's how the entire script in the template looks:

function processData(dataset) { var result = [] dataset = JSON.parse(dataset); dataset.forEach(item => result.push(item.fields)); return result; } $.ajax({ url: $("#pivot-table-container").attr("data-url"), dataType: 'json', success: function(data) { new Flexmonster({ container: "#pivot-table-container", componentFolder: "//cdn.flexmonster.com/", width: "100%", height: 430, toolbar: true, report: { dataSource: { type: "json", data: processData(data) }, slice: {} } }); new Flexmonster({ container: "#pivot-chart-container", componentFolder: "//cdn.flexmonster.com/", width: "100%", height: 430, //toolbar: true, report: { dataSource: { type: "json", data: processData(data) }, slice: {}, "options": { "viewType": "charts", "chart": { "type": "pie" } } } }); } });

Don't forget to enclose this JavaScript code in tags.

Phew! We’re nearly there with this app.

Fields customization

Flexmonster provides a special property of the data source that allows setting field data types, custom captions, and defining multi-level hierarchies.

This is a nice feature to have - we can elegantly separate data and its presentation right in the report's configuration.

Add it to the dataSource property of the report:

mapping: { "product_category": { "caption": "Product Category", "type": "string" }, "payment_method": { "caption": "Payment Method", "type": "string" }, "shipping_cost": { "caption": "Shipping Cost", "type": "number" }, "unit_price": { "caption": "Unit Price", "type": "number" } }

Dashboard's design

To make the dashboard, we’ve rendered two instances of Flexmonster (you can create as many as you want, depending on the data visualization goals you want to reach). One is for the pivot table with summarized data, and the other is for the pivot charts.

Both instances share the same data source from our model. I encourage you to try making them work in sync: with the reportchange event, you can make one instance react to the changes in another one.

You can also redefine the ‘Export’ button’s functionality on the Toolbar to make it save your reports to the server.

Results

Let’s start the Django development server and open //127.0.0.1:8000/dashboard/ to see the resulting dashboard:

Looks nice, doesn't it?

Feedback

Denne gang lærte vi, hvordan man opretter en simpel Django-app og viser dataene på klientsiden i form af et analysedashboard .

Jeg håber, du har nydt vejledningen!

Forlad venligst dine kommentarer nedenfor - enhver feedback om kodens forbedring er meget værdsat.

Referencer

Kildekoden til vejledningen kan findes på GitHub.

Og her er projektet med Flexmonster & Django integration, der inspirerede mig til denne tutorial.

Desuden anbefaler jeg at gå gennem vigtige koncepter i dokumentationen for at mestre Django:

  • Migrationer i Django
  • QuerySets
  • Serialisering af Django-objekter