django中创建多应用_如何在Django应用中创建分析仪表板

django中创建多应用

Hi folks!

嗨伙计!

Python, data visualization, and programming are the topics I'm profoundly devoted to. That’s why I’d like to share with you my ideas as well as my enthusiasm for discovering new ways to present data in a meaningful way.

Python数据可视化编程是我深入研究的主题。 这就是为什么我想与您分享我的想法以及我对发现以有意义的方式呈现数据的新方式的热情。

The case I'm going to cover is quite common: you have data on the back end of your app and want to give it shape on the front end. If such a situation sounds familiar to you, then this tutorial may come in handy.

我要介绍的情况很常见:您在应用程序的后端有数据,并且希望在前端使其成形。 如果您对这种情况听起来很熟悉,那么本教程可能会派上用场。

After you complete it, you’ll have a Django-powered app with interactive pivot tables & charts.

完成后,您将拥有一个由Django驱动的应用程序 ,该应用程序具有交互式数据透视表图表

先决条件 (Prerequisites)

To confidently walk through the steps, you need a basic knowledge of the Django framework and a bit of creativity. ✨

要自信地完成这些步骤,您需要具备Django框架的基础知识和一些创造力 。 ✨

To follow along, you can download the GitHub sample.

接下来,您可以下载GitHub示例

Here's a brief list of tools we’re going to use:

以下是我们将要使用的工具的简要列表:

If you have already set up a Django project and feel confident about the basic flow of creating apps, you can jump straight to the Connecting data to Flexmonster section that explains how to add data visualization components to it.

如果您已经设置了Django项目并且对创建应用程序的基本流程充满信心,则可以直接跳至“ 将数据连接到Flexmonster”部分,该部分说明了如何向其中添加数据可视化组件。

Let's start!

开始吧!

Django入门 (Getting started with Django)

First things first, let’s make sure you’ve installed Django on your machine. The rule of thumb is to install it in your previously set up virtual environment - a powerful tool to isolate your projects from one another.

首先,让我们确保已在计算机上安装了Django。 经验法则是将其安装在以前设置的虚拟环境中,这是一种将项目相互隔离的强大工具。

Also, make sure you’ve activated in a newly-created directory. Open your console and bootstrap a Django project with this command:

另外,请确保您已在新创建的目录中激活。 打开控制台并使用以下命令引导Django项目:

django-admin startproject analytics_project

django-admin startproject analytics_project

Now there’s a new directory called analytics_project. Let’s check if we did everything right. Go to analytics_project and start the server with a console command:

现在有一个名为analytics_project的新目录。 让我们检查一下我们是否做对了所有事情。 转到analytics_project并使用控制台命令启动服务器:

python manage.py runserver

python manage.py runserver

Open http://127.0.0.1:8000/ in your browser. If you see this awesome rocket, then everything is fine:

在浏览器中打开http://127.0.0.1:8000/ 。 如果您看到这枚超棒的火箭,那么一切都很好:

Next, create a new app in your project. Let’s name it dashboard:

接下来,在您的项目中创建一个新应用。 让我们将其命名为dashboard

python manage.py startapp dashboard

python manage.py startapp dashboard

Here's a tip: if you're not sure about the difference between the concepts of apps and projects in Django, take some time to learn about it to have a clear picture of how Django projects are organized.

提示 :如果您不确定Django中应用程序和项目的概念之间区别 ,请花一些时间来了解它,以清楚地了解Django项目的组织方式。

Here we go. Now we see a new directory within the project. It contains the following files:

开始了。 现在,我们在项目中看到一个新目录。 它包含以下文件:

__init__.py to make Python treat it as a package

__init__.py使Python将其视为包

admin.py - settings for the Django admin pages

admin.py -Django管理页面的设置

apps.py - settings for app’s configs

apps.py应用程序配置的设置

models.py - classes that will be converted to database tables by the Django’s ORM

models.py将由Django的ORM转换为数据库表的类

tests.py - test classes

tests.py测试类

views.py - functions & classes that define how the data is displayed in the templates

views.py定义数据如何在模板中显示的函数和类

Afterward, it’s necessary to register the app in the project.Go to analytics_project/settings.py and append the app's name to the INSTALLED_APPS list:

之后,有必要在应用程序中注册该应用程序。转到analytics_project/settings.py并将该应用程序的名称附加到INSTALLED_APPS列表中:

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

Now our project is aware of the app’s existence.

现在,我们的项目已经知道该应用程序的存在。

观看次数 (Views)

In the dashboard/views.py, we’ll create a function that directs a user to the specific templates defined in the dashboard/templates folder. Views can contain classes as well.

dashboard/views.py ,我们将创建一个函数,将用户定向到dashboard/templates文件夹中定义的特定模板。 视图也可以包含类。

Here’s how we define it:

这是我们的定义方式:

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', {})

Once called, this function will render dashboard_with_pivot.html - a template we'll define soon. It will contain the pivot table and pivot charts components.

调用后,此函数将呈现dashboard_with_pivot.html我们将很快定义的模板。 它将包含数据透视表和数据透视图组件。

A few more words about this function. Its request argument, an instance of HttpRequestObject, contains information about the request, e.g., the used HTTP method (GET or POST). The method render searches for HTML templates in a templates directory located inside the app’s directory.

关于此功能的更多信息。 它的request参数是HttpRequestObject的实例,包含有关请求的信息,例如,使用的HTTP方法(GET或POST)。 该方法render在应用程序目录内的templates目录中搜索HTML模板。

We also need to create an auxiliary method that sends the response with data to the pivot table on the app's front-end. Let's call it pivot_data:

我们还需要创建一个辅助方法,该方法将带有数据的响应发送到应用程序前端的数据透视表。 我们称它为pivot_data

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

Likely, your IDE is telling you that it can’t find a reference Order in models.py. No problem - we’ll deal with it later.

您的IDE可能会告诉您,它无法在models.py找到参考Order 。 没问题-我们稍后再处理。

范本 (Templates)

For now, we’ll take advantage of the Django template system.

现在,我们将利用Django模板系统。

Let's create a new directory templates inside dashboard and create the first HTML template called dashboard_with_pivot.html. It will be displayed to the user upon request. Here we also add the scripts and containers for data visualization components:

让我们在dashboard内创建一个新的目录templates ,并创建第一个HTML模板,名为dashboard_with_pivot.html 。 根据要求将其显示给用户。 在这里,我们还为数据可视化组件添加了脚本和容器:

<head>
  <meta charset="UTF-8">
  <title>Dashboard with Flexmonster</title>
  <script src="https://cdn.flexmonster.com/flexmonster.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <link rel="stylesheet" href="https://cdn.flexmonster.com/demo.css">
</head>
<body>
<div id="pivot-table-container" data-url="{% url 'pivot_data' %}"></div>
<div id="pivot-chart-container"></div>
</body>

将视图功能映射到URL
(Mapping views functions to URLs)

To call the views and display rendered HTML templates to the user, we need to map the views to the corresponding URLs.

要调用视图并将渲染HTML模板显示给用户,我们需要将视图映射到相应的URL。

Here's a tip: one of Django's URL design principles says about loose coupling, we shouldn't make URLs with the same names as Python functions.

提示: Django的URL设计原则之一是关于松散耦合的 ,我们不应该使URL与Python函数具有相同的名称。

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

转到analytics_app/urls.py并在项目级别为dashboard应用程序添加相关配置。

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.

现在,可以访问dashboard应用程序中的URL,但前提是它们必须以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:

之后,转到dashboard/urls.py (如果此文件不存在,则创建此文件)并添加映射到视图功能的URL模式列表:

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.

由于本教程的目的是演示如何在应用程序内部构建交互式数据可视化,因此我们不必担心数据库的选择。 我们将使用SQLite -Django Web开发服务器随附的轻量级数据库。

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.

但是请记住,此数据库不是生产开发的适当选择。 使用Django ORM,您可以使用其他使用SQL语言的数据库,例如PostgreSQL或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:

想象我们正在为销售部门设计一个仪表板 。 因此,让我们创建一个Order类,并在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.

这就是迁移概念派上用场的地方。 迁移只是一个描述必须将哪些更改应用于数据库的文件。 每次我们需要基于Python类描述的模型创建数据库时,都使用迁移。

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.

数据可能以Python对象,字典或列表的形式出现。 这次,我们将使用models目录中的Python类表示数据库中的实体。

Create migration for the app with one command:

使用一个命令为应用创建迁移:

python manage.py makemigrations dashboard

python manage.py makemigrations dashboard

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

在这里,我们指定应用程序应告诉Django为dashboard应用程序的模型应用迁移。

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

创建迁移文件后,应用其中描述的迁移并创建数据库:

python manage.py migrate dashboard

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.

如果您在项目目录中看到一个新文件db.sqlite3 ,则可以使用该数据库了。

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.

让我们创建Order类的实例。 为此,我们将使用Django Shell-与Python Shell相似,但允许访问数据库并创建新条目。

So, start the Django shell:

因此,启动Django shell:

python manage.py 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.

同样,您可以根据需要创建和保存尽可能多的对象。

将数据连接到Flexmonster (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:

为了使后端和Flexmonster进行通信,我们可以采用两种不同的方法:

  • Using the request-response cycle. We can use Python and the Django template engine to write JavaScript code directly in the template.

    使用请求-响应周期。 我们可以使用Python和Django模板引擎直接在模板中编写JavaScript代码。

  • Using an async request (AJAX) that returns the data in JSON.

    使用异步请求(AJAX)以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.

在我看来,第二个原因最方便,原因有很多。 首先,Flexmonster理解JSON。 确切地说,它可以接受JSON对象数组作为输入数据。 使用异步请求的另一个好处是更好的页面加载速度和更可维护的代码。

Let's see how it works.

让我们看看它是如何工作的。

Go to the templates/dashboard_pivot.html.

转到templates/dashboard_pivot.html

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

在这里,我们创建了两个div容器,将在其中渲染数据透视表网格和数据透视表。

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).

在ajax调用中,我们根据data-URL属性中包含的URL发出请求。 然后,我们告诉ajax请求我们期望返回一个JSON对象(由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.

请求完成后,我们的服务器返回的JSON响应将设置为data参数,并显示填充有该数据的数据透视表。

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.

查询结果( JSONResponse的实例)返回一个字符串,该字符串包含带有额外元信息的数组对象,因此我们应该在前端添加一个用于数据处理的小函数。 它将仅提取我们需要的那些嵌套对象,并将它们放入单个数组中。 这是因为Flexmonster接受不带嵌套级别的JSON对象数组。

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: "https://cdn.flexmonster.com/",
            width: "100%",
            height: 430,
            toolbar: true,
            report: {
                dataSource: {
                    type: "json",
                    data: processData(data)
                },
                slice: {}
            }
        });
        new Flexmonster({
            container: "#pivot-chart-container",
            componentFolder: "https://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 <script> tags.

不要忘记将此JavaScript代码括在<script>标记中。

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.

Flexmonster提供了数据源的特殊属性,该属性允许设置字段数据类型,自定义标题和定义多级层次结构。

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:

将其添加到报表的dataSource属性中:

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.

为了制作仪表板,我们渲染了两个Flexmonster实例(您可以创建任意数量的实例,具体取决于要达到的数据可视化目标)。 一个用于带有汇总数据的数据透视表,另一个用于数据透视图。

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.

两个实例共享来自我们模型的相同数据源。 我鼓励您尝试使它们同步工作:通过reportchange事件,您可以使一个实例对另一个实例的更改做出React。

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 http://127.0.0.1:8000/dashboard/ to see the resulting dashboard:

让我们启动Django开发服务器并打开http://127.0.0.1:8000/dashboard/以查看生成的仪表板:

Looks nice, doesn't it?

看起来不错,不是吗?

反馈
(Feedback)

This time we learned how to create a simple Django app and display the data on the client side in the form of an analytics dashboard.

这次,我们学习了如何创建一个简单的Django应用程序以及如何以 分析仪表板的形式在客户端显示数据。

I do hope you enjoyed the tutorial!

我希望您喜欢本教程!

Please leave your comments below - any feedback on the code’s improvement is highly appreciated.

请在下面留下您的评论-非常感谢您对代码改进的任何反馈。

参考文献
(References)

The source code for the tutorial can be found on GitHub.

该教程的源代码可以在GitHub找到

And here’s the project with Flexmonster & Django integration that inspired me for this tutorial.

这是Flexmonster和Django集成的项目,启发了我学习本教程。

Further, I recommend walking through important concepts in the documentation to master Django:

此外,我建议您逐步阅读文档中的重要概念以掌握Django:

翻译自: https://www.freecodecamp.org/news/how-to-create-an-analytics-dashboard-in-django-app/

django中创建多应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值