Bok, zajednica freeCodeCamp!
U ovom uputstvu želio bih podijeliti s vama pristup vizualizaciji podataka u Pythonu koji možete dalje primijeniti u razvoju Djanga.
Ako ste ikada naišli na potrebu za izgradnjom interaktivne nadzorne ploče ili biste to pokušali učiniti, slobodno prođite kroz korake iz ovog vodiča.
Ako imate bilo kakvih pitanja u vezi s postupkom, postavite ih u komentarima. Rado ću vam pomoći.
Evo popisa vještina koje ćete svladati nakon završetka tutorijala:
- Kako stvoriti osnovnu Django aplikaciju
- Kako hostirati udaljene MongoDB podatke u MongoDB Atlas
- Kako uvesti JSON i CSV podatke u MongoDB
- Kako dodati alat za izvještavanje u aplikaciju Django
Počnimo! ?? ??? ?
Preduvjeti
- Osnovna znanja o web razvoju
- Pouzdano znanje Pythona
- Osnovno iskustvo s NoSQL bazama podataka (npr. MongoDB)
Alati
- Django - Python internetski okvir visoke razine.
- MongoDB Atlas - usluga baze podataka u oblaku za moderne aplikacije. Ovdje ćemo ugostiti našu MongoDB bazu podataka.
- Zaokretna tablica i grafikoni Flexmonster - JavaScript web komponenta za izvještavanje. Obrađivat će zadatke vizualizacije podataka na klijentskoj strani.
- MongoDB konektor za Flexmonster - alat na strani poslužitelja za brzu komunikaciju između zaokretne tablice i MongoDB-a.
- Izdanje zajednice PyCharm - IDE za razvoj Pythona.
- Kaggle podaci
Uspostavite Django projekt
Ako ste novi u razvoju Djanga, to je u redu. Postepeno ćemo postaviti sve kako bi naša prijava bila izvanredna.
- Provjerite jeste li prethodno instalirali Django na svoj stroj.
- Prvo otvorite direktorij u kojem želite da se vaš projekt kreira. Otvorite konzolu i pokrenite sljedeću naredbu da biste stvorili novi sjajni Django projekt:
django-admin startproject django_reporting_project
- Zatim idite na ovaj projekt:
cd django_reporting_project
- Provjerimo radi li sve prema očekivanjima. Pokrenite Django poslužitelj:
python manage.py runserver
Ako nije drugačije naznačeno, razvojni poslužitelj započinje na portu 8000 . Otvorite //127.0.0.1:8000/
u pregledniku. Ako možete vidjeti ovu cool raketu, na dobrom smo putu!

Izradite aplikaciju
Sada je vrijeme da izradimo našu aplikaciju osnaženu značajkama izvještavanja.
Ako se ne osjećate sigurni u razliku između projekata i aplikacija u Djangu, evo kratke reference koja će vam pomoći da to shvatite.- Nazovimo to
dashboard
:
python manage.py startapp dashboard
- Zatim otvorite projekt u svom omiljenom IDE-u. Toplo preporučujem upotrebu PyCharma jer čitav proces programiranja u Pythonu čini blaženstvom. Također prikladno upravlja stvaranjem izoliranog virtualnog okruženja specifičnog za projekt.
- Nakon izrade aplikacije potrebno ju je registrirati na razini projekta. Otvorite
django_reporting_project/settings.py
datoteku i dodajte ime aplikacije na krajINSTALLED_APPS
popisa:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', ]
Ura! Sada projekt zna za postojanje vaše aplikacije i spremni smo prijeći na konfiguraciju baze podataka.
Postavite MongoDB bazu podataka pomoću MongoDB Atlas
Ostavimo aplikaciju sa strane dok ne završimo s uređivanjem naše baze podataka. Predlažem da vježbamo u stvaranju udaljene baze podataka MongoDB tako što ćemo je smjestiti na MongoDB Atlas - uslugu baze podataka u oblaku za aplikacije. Alternativno, možete pripremiti lokalnu bazu podataka i raditi s njom na bilo koji prikladan način (npr. Putem MongoDB Compassa ili mongo ljuske).
- Nakon što se prijavite na svoj MongoDB račun, izradite naš prvi projekt. Nazovimo to
ECommerceData
:

- Zatim dodajte članove (ako je potrebno) i postavite dozvole. Možete pozvati korisnike da sudjeluju u vašem projektu putem adrese e-pošte.
- Stvorite klaster:

- Odaberite plan. Budući da smo na putu učenja, najjednostavniji besplatni plan bit će dovoljan za naše potrebe.
- Odaberite davatelja usluga u oblaku i regiju. Preporučena područja zaključuju se putem vašeg mjesta i označavaju zvjezdicama.
- Dajte suvislo ime našem potpuno novom klasteru. Imajte na umu da se kasnije ne može mijenjati. Nazovimo to
ReportingData
:

Pripremite podatke
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
mongoimport
command 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 (insidedashboard
). 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.html
which 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 href
property 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.
- In templates, create
marketing_report.html
. - Add an extends tag to inherit from the basic template:
{% extends "base.html" %}
- Add a block tag to define our child template's content:
{% block content %}
{% endblock %}
- Within the block, add Flexmonster scripts and containers where the reporting components will be placed (i.e., the pivot table and pivot charts):
- 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:
- connects to the MongoDB database
- gets the collection’s structure
- queries data every time the report’s structure is changed
- 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.ts
you 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" } }