Hoe u een webgebaseerd dashboard bouwt met Django, MongoDB en draaitabel

Hallo, de freeCodeCamp-community!

In deze tutorial wil ik een benadering van datavisualisatie in Python met je delen die je verder kunt toepassen in de Django-ontwikkeling.

Als u ooit de noodzaak bent tegengekomen om een interactief dashboard te bouwen of als u het wilt proberen, kunt u de stappen van deze zelfstudie doorlopen.

Als u vragen heeft over het proces, stel deze dan in de opmerkingen. Ik help u graag verder.

Hier is de lijst met vaardigheden die je gaat beheersen na voltooiing van de tutorial:

  • Hoe maak je een eenvoudige Django- app
  • Hoe MongoDB- gegevens op afstand te hosten in MongoDB Atlas
  • JSON- en CSV- gegevens importeren in MongoDB
  • Hoe u een rapportagetool toevoegt aan de Django-app

Laten we beginnen! ?? ‍ ??? ‍?

Vereisten

  • Basiskennis van webontwikkeling
  • Zelfverzekerde kennis van Python
  • Basiservaring met NoSQL- databases (bijvoorbeeld MongoDB)

Hulpmiddelen

  • Django - een Python-webframework op hoog niveau.
  • MongoDB Atlas - een clouddatabaseservice voor moderne toepassingen. Hier zullen we onze MongoDB-database hosten.
  • Flexmonster Pivot Table & Charts - een JavaScript- webcomponent voor rapportage. Het behandelt datavisualisatietaken aan de klantzijde.
  • De MongoDB-connector voor Flexmonster - een server-side tool voor snelle communicatie tussen Pivot Table en MongoDB.
  • PyCharm Community Edition - een IDE voor Python-ontwikkeling.
  • Kaggle- gegevens

Zet een Django-project op

Als Django-ontwikkeling nieuw voor je is, is dat prima. Stap voor stap zetten we alles op alles om onze applicatie uitmuntend te maken.

  • Zorg ervoor dat je Django eerder op je computer hebt geïnstalleerd.
  • Open eerst de map waarin u uw project wilt maken. Open de console en voer de volgende opdracht uit om een ​​nieuw glanzend Django-project te maken:

django-admin startproject django_reporting_project

  • Navigeer vervolgens naar dit project:

cd django_reporting_project

  • Laten we eens kijken of alles werkt zoals verwacht. Start de Django-server:

python manage.py runserver

Tenzij anders aangegeven, start de ontwikkelserver op poort 8000 . Open //127.0.0.1:8000/in uw browser. Als je deze coole raket kunt zien, zijn we op de goede weg!

Maak een app

Nu is het tijd om onze applicatie te maken met rapportagefuncties.

Als je geen vertrouwen hebt in het verschil tussen projecten en applicaties in Django, dan is hier een korte referentie om je te helpen erachter te komen.
  • Laten we het noemen dashboard:

python manage.py startapp dashboard

  • Open vervolgens het project in uw favoriete IDE. Ik raad het ten zeerste aan om PyCharm te gebruiken, omdat het het hele proces van programmeren in Python een zaligheid maakt. Het beheert ook gemakkelijk de creatie van een projectspecifieke geïsoleerde virtuele omgeving.
  • Nadat een app is gemaakt, moet deze op projectniveau worden geregistreerd. Open het django_reporting_project/settings.pybestand en voeg de naam van de app toe aan het einde van de INSTALLED_APPSlijst:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', ]

Hoera! Nu weet het project van het bestaan ​​van uw app en zijn we klaar om verder te gaan met de databaseconfiguratie.

Stel een MongoDB-database in met MongoDB Atlas

Laten we de app opzij zetten totdat we klaar zijn met het inrichten van onze database. Ik stel voor dat we oefenen met het maken van de MongoDB-database op afstand door deze te hosten op MongoDB Atlas - een clouddatabaseservice voor applicaties. Als alternatief kunt u een lokale database voorbereiden en er op een willekeurige manier mee werken (bijv. Via MongoDB Compass of de mongo-shell).

  • Nadat u zich heeft aangemeld met uw MongoDB-account, maakt u ons eerste project aan. Laten we het maar noemen ECommerceData:
  • Voeg vervolgens leden toe (indien nodig) en stel machtigingen in. U kunt gebruikers via een e-mailadres uitnodigen om deel te nemen aan uw project.
  • Maak een cluster:
  • Kies het plan. Omdat we op ons leertraject zitten, is het eenvoudigste gratis plan voldoende voor onze behoeften.
  • Selecteer een cloudprovider en regio. De aanbevolen regio's worden afgeleid uit uw locatie en gemarkeerd met sterren.
  • Geef een betekenisvolle naam aan ons gloednieuwe cluster. Merk op dat het later niet kan worden gewijzigd. Laten we het maar noemen ReportingData:

Bereid gegevens voor

While you’re waiting for your cluster to be created, let’s take a closer look at the data we’ll be working with. For this tutorial, we’re going to use the Kaggle dataset with transactions from a UK retailer. Using this data, we’ll try constructing a meaningful report which can serve for exploratory data analysis within a real organization.

Additionally, we’re going to use mock JSON data about marketing. It will help us to achieve the goal of establishing different reporting tools within the same application. You can choose any data of your preference.

Connect to your cluster

Now that our cluster is ready, let’s connect to it!

  • Whitelist your current IP address or add a different one.
  • Create a MongoDB user. The first one will have atlasAdmin permissions for the current project which means possessing the following roles and privilege actions. For security reasons, it’s recommended to auto-generate a strong password.
  • Choose a connection method that suits you best. To test the connection, we can use the connection string for the mongo shell first. Later we’ll also use a connection string for an application.
  • Connect to it via the mongo shell. Open the command line and run the following:

mongo "mongodb+srv://reportingdata-n8b3j.mongodb.net/test"  --username yourUserName

The interactive prompt will ask you for a password to authenticate.

Check cluster metrics

Phew! We’re almost there.

Now get back to the page with the cluster summary and see how it came to life! From now, we can gain insights into write and read operations of the MongoDB database, the number of active connections, the logical size of our replica set - all this statistical information is at your hand. But most importantly now it’s possible to create and manage databases and collections.

Create a database

Create your first database and two collections. Let’s name them ecommerce,transactions, and marketing correspondingly.

Here’s how our workspace looks like now:

Looks quite empty, doesn’t it?

Import data to MongoDB

Let’s populate the collection with data. We’ll start with the retail data previously downloaded from Kaggle.

  • Unzip the archive and navigate to the directory where its contents are stored.
  • Next, open the command prompt there and import the data to the transactions collection of the ecommerce database using the mongoimportcommand and the given connection string for the mongo shell:

mongoimport --uri "mongodb+srv://username:[email protected]/ecommerce?retryWrites=true&w=majority" --collection transactions --drop --type csv --headerline --file data.csv

❗Please remember to replace username and password keywords with your credentials.

Congrats! We’ve just downloaded 541909 documents to our collection. What’s next?

  • Upload the dataset with marketing metrics to the marketing collection. Here’s the JSON file with the sample data we’re going to use.

Import the JSON array into the collection using the following command:

mongoimport --uri "mongodb+srv://username:[email protected]/ecommerce?retryWrites=true&w=majority" --collection marketing --drop --jsonArray marketing_data.json

If this data is not enough, we could dynamically generate more data using the mongoengine / PyMongo models. This is what our next tutorial of this series will be dedicated to. But for now, we’ll skip this part and work with the data we already have.

Now that our collections contain data, we can explore the number of documents in each collection as well as their structure. For more insights, I’d recommend using MongoDB Compass which is the official GUI tool for MongoDB. With it, you can explore the structure of each collection, check the distribution of field types, build aggregation pipelines, run queries, evaluate and optimize their performance. To start, download the application and use the connection string for Compass provided by MongoDB Atlas.

Map URL patterns to views

Let’s get back to Django.

  • Create urls.py in the app’s folder (inside dashboard). Here we’ll store URL routes for our application. These URL patterns will be matched with views defined indashboard/views.py:
from django.urls import path from . import views urlpatterns = [ path('report/retail', views.ecommerce_report_page, name="retail_report"), path('report/marketing', views.marketing_report_page, name="marketing_report"), ] 
  • The application’s URLs need to be registered at the project’s level. Open django-reporting-project/urls.py and replace the contents with the following code:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), ]

Create views

A view is simply a function that accepts a web request and returns a web response. The response can be of any type. Using the render() function, we’ll be returning an HTML template and a context combined into a single HttpResponse object. Note that views in Django can also be class-based.

  • In dashboard/views.py let’s create two simple views for our reports:
from django.shortcuts import render def ecommerce_report_page(request): return render(request, 'retail_report.html', {}) def marketing_report_page(request): return render(request, 'marketing_report.html', {}) 

Create templates

  • Firstly, create the templates folder inside your app’s directory. This is where Django will be searching for your HTML pages.

  • Next, let’s design the layout of our application. I suggest we add a navigation bar that will be displayed on every page. For this, we’ll create a basic template called base.htmlwhich all other pages will extend according to business logic. This way we'll take advantage of template inheritance - a powerful part of the Django’s template engine. Please find the HTML code on GitHub.

As you may have noticed, we’re going to use Bootstrap styles. This is to prettify our pages with ready-to-use UI components.

Note that in the navigation bar, we’ve added two links that redirect to the report pages. You can do it by setting the link's hrefproperty to the name of the URL pattern, specified by the name keyword in the URL pattern. For example, in the following way:

href="{% url 'marketing_report' %}"

  • It's time to create pages where the reports will be located. Let me show you how to create a retail report first. By following these principles, you can create as many other reporting pages as you need.
  1. In templates, create marketing_report.html.
  2. Add an extends tag to inherit from the basic template: {% extends "base.html" %}
  3. Add a block tag to define our child template's content:{% block content %}

    {% endblock %}

  4. Within the block, add Flexmonster scripts and containers where the reporting components will be placed (i.e., the pivot table and pivot charts):

  5. Add tags where JavaScript code will be executed. Within these tags, instantiate two Flexmonster objects using init API calls.
var pivot = new Flexmonster({ container: "#pivot", componentFolder: "//cdn.flexmonster.com/", height: 600, toolbar: true, report: {} }); var pivot_charts = new Flexmonster({ container: "#pivot_charts", componentFolder: "//cdn.flexmonster.com/", height: 600, toolbar: true, report: {} });

You can place as many Flexmonster components as you want. Later, we’ll fill these components with data and compose custom reports.

Set up the MongoDB connector

To establish efficient communication between Flexmonster Pivot Table and the MongoDB database, we can use the MongoDB Connector provided by Flexmonster. This is a server-side tool that does all the hard work for us, namely:

  1. connects to the MongoDB database
  2. gets the collection’s structure
  3. queries data every time the report’s structure is changed
  4. sends aggregated data back to show it in the pivot table.

To run it, let’s clone this sample from GitHub, navigate to its directory, and install the npm packages by running npm install.

  • In src/server.tsyou can check which port the connector will be running on. You can change the default one. Here, you can also specify which module will handle requests coming to the endpoint ( mongo.ts in our case).
  • After, specify the database credentials in src/controller/mongo.ts. Right there, add the connector string for application provided by MongoDB Atlas and specify the database’s name.

Define reports

Now we’re ready to define the report’s configuration on the client side.

  • Here’s a minimal configuration which makes the pivot table work with the MongoDB data via the connector:
var pivot = new Flexmonster({ container: "#pivot", componentFolder: "//cdn.flexmonster.com/", height: 600, toolbar: true, report: { "dataSource": { "type": "api", "url": "//localhost:9204/mongo", // the url where our connector is running "index": "marketing" // specify the collection’s name }, "slice": {} } });
  • Specify a slice - the set of hierarchies that will be shown on the grid or on the chart. Here’s the sample configuration for the pivot grid.

"slice": { "rows": [ { "uniqueName": "Country" } ], "columns": [ { "uniqueName": "[Measures]" } ], "measures": [ { "uniqueName": "Leads", "aggregation": "sum" }, { "uniqueName": "Opportunities", "aggregation": "sum" } ] }

Run your reporting app

Now that we’ve configured the client side, let’s navigate to the MongoDB connector’s directory and run the server:

npm run build

npm run start

  • Next, return to the PyCharm project and run the Django server:

    python manage.py runserver

  • Open //127.0.0.1:8000/report/marketing. To switch to another report, click the report’s name on the navigation bar.

It’s time to evaluate the results! Here you can see the report for the marketing department:

Try experimenting with the layout:

  • Slice & dice the data to get your unique perspective.
  • Change summary functions, filter & sort the records.
  • Switch between classic and compact form to know what feels better.

Enjoy analytics dashboard in Python

Congratulations! Excellent work. We’ve brought our data to life. Now you have a powerful Django application enabled with reporting and data visualization functionality.

The thing your end-users may find extremely comfy is that it’s possible to configure a report, save it, and pick up where you left off later by uploading it into the pivot table. Reports are neat JSON files that can be stored locally or to the server. Also, it’s possible to export reports into PDF, HTML, Image, or Excel files.

Feel free to tailor the app according to your business requirements! You can add more complex logic, change the data source (e.g., MySQL, PostgreSQL, Oracle, Microsoft Analysis Services, Elasticsearch, etc), and customize the appearance and/or the functionality of the pivot table and pivot charts.

Further reading

  • Full code on GitHub
  • A comprehensive guide on how to get started with MongoDB Atlas
  • Getting started with Flexmonster Pivot Table & Charts
  • Getting started with Django
  • Introduction to the MongoDB connector
  • The MongoDB connector API
  • How to change report themes
  • How to localize the pivot table component

Extra settings to prettify your report

Here's an additional section for curious minds!

To prettify the hierarchies’ captions and define field types, we’ll add mapping - a special object in the data source configuration of the report. Mapping helps us define how to display field names by setting captions. Plus, it’s possible to explicitly define types of fields (numbers, strings, different types of dates). Every piece of configuration depends on your business logic.

Generally speaking, mapping creates an additional level of abstraction between the data source and its representation.

Here’s an example of how it can be defined for the retail dataset:

"mapping": { "InvoiceNo": { "caption": "Invoice Number", "type": "string" }, "StockCode": { "caption": "Stock Code", "type": "string" }, "Description": { "type": "string" }, "Quantity": { "type": "number" }, "InvoiceDate": { "type": "string", "caption": "Invoice Date" }, "UnitPrice": { "type": "number", "caption": "Unit Price" }, "CustomerID": { "type": "string", "caption": "Customer ID" }, "Country": { "type": "string" } }