`

dashborad 增加action

阅读更多
============================================
Tutorial: Adding a complex action to a table
============================================

This tutorial covers how to add a more complex action to a table, one that requires
an action and form definitions, as well as changes to the view, urls, and table.

This tutorial assumes you have already completed :doc:`Building a Dashboard using
Horizon  </tutorials/dashboard>`. If not, please do so now as we will be modifying the
files created there.
首先建好一个dashboard并带有tables
This action will create a snapshot of the instance. When the action is taken,
it will display a form that will allow the user to enter a snapshot name,
and will create that snapshot when the form is closed using the ``Create snapshot``
button.

Defining the view
=================

To define the view, we must create a view class, along with the template (``HTML``)
file and the form class for that view.

The template file
-----------------
The template file contains the HTML that will be used to show the view.

Create a ``create_snapshot.html`` file under the ``mypanel/templates/mypanel``
directory and add the following code::

  
 
create_snapshot.html{% extends 'base.html' %}
    {% load i18n %}
    {% block title %}{% trans "Create Snapshot" %}{% endblock %}

    {% block page_header %}
      {% include "horizon/common/_page_header.html" with title=_("Create a Snapshot") %}
    {% endblock page_header %}

    {% block main %}
        {% include 'mydashboard/mypanel/_create_snapshot.html' %}
    {% endblock %}



As you can see, the main body will be defined in ``_create_snapshot.html``,
so we must also create that file under the ``mypanel/templates/mypanel``
directory. It should contain the following code::

   
_create_snapshot.html
{% extends "horizon/common/_modal_form.html" %}
    {% load i18n %}

    {% block modal-body-right %}
        <h3>{% trans "Description:" %}</h3>
        <p>{% trans "Snapshots preserve the disk state of a running instance." %}</p>
    {% endblock %}



The form
--------

Horizon provides a :class:`~horizon.forms.base.SelfHandlingForm` class which simplifies
some of the details involved in creating a form. Our form will derive from this
class, adding a character field to allow the user to specify a name for the
snapshot, and handling the successful closure of the form by calling the nova
api to create the snapshot.

Create the ``forms.py`` file under the ``mypanel`` directory and add the following::
forms.py
    from django.core.urlresolvers import reverse
    from django.utils.translation import ugettext_lazy as _

    from horizon import exceptions
    from horizon import forms

    from openstack_dashboard import api


    class CreateSnapshot(forms.SelfHandlingForm):
        instance_id = forms.CharField(label=_("Instance ID"),
                                      widget=forms.HiddenInput(),
                                      required=False)
        name = forms.CharField(max_length=255, label=_("Snapshot Name"))

        def handle(self, request, data):
            try:
                snapshot = api.nova.snapshot_create(request,
                                                    data['instance_id'],
                                                    data['name'])
                return snapshot
            except Exception:
                exceptions.handle(request,
                                  _('Unable to create snapshot.'))


The view
--------

Now, the view will tie together the template and the form. Horizon provides a
:class:`~horizon.forms.views.ModalFormView` class which simplifies the creation of a
view that will contain a modal form.

Open the ``views.py`` file under the ``mypanel`` directory and add the code
for the CreateSnapshotView and the necessary imports. The complete
file should now look something like this::
views.py
    from django.core.urlresolvers import reverse
    from django.core.urlresolvers import reverse_lazy
    from django.utils.translation import ugettext_lazy as _

    from horizon import tabs
    from horizon import exceptions
    from horizon import forms

    from horizon.utils import memoized

    from openstack_dashboard import api

    from openstack_dashboard.dashboards.mydashboard.mypanel \
        import forms as project_forms

    from openstack_dashboard.dashboards.mydashboard.mypanel \
        import tabs as mydashboard_tabs


    class IndexView(tabs.TabbedTableView):
        tab_group_class = mydashboard_tabs.MypanelTabs
        # A very simple class-based view...
        template_name = 'mydashboard/mypanel/index.html'

        def get_data(self, request, context, *args, **kwargs):
            # Add data to the context here...
            return context


    class CreateSnapshotView(forms.ModalFormView):
        form_class = project_forms.CreateSnapshot
        template_name = 'mydashboard/mypanel/create_snapshot.html'
        success_url = reverse_lazy("horizon:project:images:index")
        modal_id = "create_snapshot_modal"
        modal_header = _("Create Snapshot")
        submit_label = _("Create Snapshot")
        submit_url = "horizon:mydashboard:mypanel:create_snapshot"

        @memoized.memoized_method
        def get_object(self):
            try:
                return api.nova.server_get(self.request,
                                           self.kwargs["instance_id"])
            except Exception:
                exceptions.handle(self.request,
                                  _("Unable to retrieve instance."))

        def get_initial(self):
            return {"instance_id": self.kwargs["instance_id"]}

        def get_context_data(self, **kwargs):
            context = super(CreateSnapshotView, self).get_context_data(**kwargs)
            instance_id = self.kwargs['instance_id']
            context['instance_id'] = instance_id
            context['instance'] = self.get_object()
            context['submit_url'] = reverse(self.submit_url, args=[instance_id])
            return context



Adding the url
==============

We must add the url for our new view.  Open the ``urls.py`` file under
the ``mypanel`` directory and add the following as a new url pattern::
urls.py
    url(r'^(?P<instance_id>[^/]+)/create_snapshot/$',
        views.CreateSnapshotView.as_view(),
        name='create_snapshot'),

The complete ``urls.py`` file should look like this::

    from django.conf.urls import patterns
    from django.conf.urls import url

    from openstack_dashboard.dashboards.mydashboard.mypanel import views


    urlpatterns = patterns('',
        url(r'^$',
            views.IndexView.as_view(), name='index'),
        url(r'^(?P<instance_id>[^/]+)/create_snapshot/$',
            views.CreateSnapshotView.as_view(),
            name='create_snapshot'),
    )



Define the action
=================

Horizon provides a :class:`~horizon.tables.LinkAction` class which simplifies
adding an action which can be used to display another view.

We will add a link action to the table that will be accessible from each row
in the table. The action will use the view defined above to create a snapshot
of the instance represented by the row in the table.

To do this, we must edit the ``tables.py`` file under the ``mypanel`` directory
and add the following::
tables.py
    def is_deleting(instance):
        task_state = getattr(instance, "OS-EXT-STS:task_state", None)
        if not task_state:
            return False
        return task_state.lower() == "deleting"


    class CreateSnapshotAction(tables.LinkAction):
        name = "snapshot"
        verbose_name = _("Create Snapshot")
        url = "horizon:mydashboard:mypanel:create_snapshot"
        classes = ("ajax-modal",)
        icon = "camera"

        # This action should be disabled if the instance
        # is not active, or the instance is being deleted
        def allowed(self, request, instance=None):
            return instance.status in ("ACTIVE") \
                and not is_deleting(instance)


We must also add our new action as a row action for the table::

    row_actions = (CreateSnapshotAction,)


The complete ``tables.py`` file should look like this::

    from django.utils.translation import ugettext_lazy as _

    from horizon import tables


    def is_deleting(instance):
        task_state = getattr(instance, "OS-EXT-STS:task_state", None)
        if not task_state:
            return False
        return task_state.lower() == "deleting"


    class CreateSnapshotAction(tables.LinkAction):
        name = "snapshot"
        verbose_name = _("Create Snapshot")
        url = "horizon:mydashboard:mypanel:create_snapshot"
        classes = ("ajax-modal",)
        icon = "camera"

        def allowed(self, request, instance=None):
            return instance.status in ("ACTIVE") \
                and not is_deleting(instance)


    class MyFilterAction(tables.FilterAction):
        name = "myfilter"


    class InstancesTable(tables.DataTable):
        name = tables.Column("name", verbose_name=_("Name"))
        status = tables.Column("status", verbose_name=_("Status"))
        zone = tables.Column('availability_zone', verbose_name=_("Availability Zone"))
        image_name = tables.Column('image_name', verbose_name=_("Image Name"))

        class Meta:
            name = "instances"
            verbose_name = _("Instances")
            table_actions = (MyFilterAction,)  //定义表格上方的按钮
            row_actions = (CreateSnapshotAction,)  //定义表格中的按钮


Run and check the dashboard
===========================

We must once again run horizon to verify our dashboard is working::

    ./run_tests.sh --runserver 0.0.0.0:8877


Go to ``http://<your server>:8877`` using a browser. After login as an admin,
display ``My Panel`` to see the ``Instances`` table. For every ``ACTIVE``
instance in the table, there will be a ``Create Snapshot`` action on the row.
Click on ``Create Snapshot``, enter a snapshot name in the form that is shown,
then click to close the form. The ``Project Images`` view should be shown with
the new snapshot added to the table.


Conclusion
==========

What you've learned here is the fundamentals of how to add a table action that
requires a form for data entry. This can easily be expanded from creating a
snapshot to other API calls that require more complex forms to gather the
necessary information.

If you have feedback on how this tutorial could be improved, please feel free
to submit a bug against ``Horizon`` in `launchpad`_.

    .. _launchpad: https://bugs.launchpad.net/horizon
分享到:
评论

相关推荐

    Dashborad 4.0

    BO Dashborad 4.0 Help

    dashborad项目

    在这个"dashborad-project-master"压缩包中,我们可以预见到一个包含源代码和资源的主分支或版本。 在HTML项目中,我们通常会找到以下关键组成部分: 1. **HTML文件**:这些是项目的核心,如`index.html`,它们...

    微服务springcloud之dashboard使用demo(仪表盘)

    针对生产环境, Netflix还给我们准备了一个非常好用的运维工具, 那就是Hystrix Dashboard,通过Hystrix Dashboard我们可以在直观地看到各Hystrix Command的请求响应时间, 请求成功率等数据. 但是只使用Hystrix ...

    Flask-Admin-Dashboard-Summary:带摘要行的Flask-Admin-Dashboard

    带摘要的Flask-Admin仪表盘 创建该项目是为了响应该SO问题。 该问题引用了先前的SO问题,即 。 该项目是的克隆,带有一个额外的视图(项目),该视图显示了如何向列表视图添加摘要行。 该项目与原始项目不同: 使用...

    macrodashboard:宏仪表板

    宏仪表板 此回购包含构建与Grattan Institute的宏观经济政策工作相关的图形的闪亮仪表板。 这是一项未完成的工作。 可以在以下位置找到实时仪表板: : 数据 仪表板的所有数据均通过macro_dashboard_data库提供,...

    terraform-kerberus-dashboard

    Terraform Kerberus仪表板 Terraform模块可在您的Kubernates上创建部署Kerberus仪表板。 用法 module " kerberus_dashboard " { source = " project-kerberus/dashboard/kerberus " ... argocd_token = " hjudshf3jcu...

    React-Dashboard-UI:React Dashborad用户界面

    React仪表板用户界面Netlify: ://react-dashboard-ui.netlify.app桌面检视移动响应式Create React App入门该项目是通过引导的。可用脚本在项目目录中,可以运行: yarn start 在开发模式下运行该应用程序。...

    Dashborad:基于laravel,vue和bulma的阿拉伯语管理控制台

    Laravel DashBoard演示 特征 基于Laravel的样板包含有用的Vue组件,例如:dropzone,编辑器,上传器,地图,多选,甜蜜警报,图标和颜色选择器。 用布尔玛制成的阿拉伯风格,并包含站立包,例如: ...

    能耗分析系统中心端Dashboard界面HTML+JS+CSS源代码.zip

    数据分析能耗分析系统中心端Dashboard界面HTML+JS+CSS源代码.zip

    React-TypeScript-Dashboard-Template:使用TypeScipt的React仪表板模板

    Create React App入门该项目是通过。可用脚本在项目目录中,可以运行:yarn start 在开发模式下运行应用程序。 打开在浏览器中查看。 如果进行编辑,页面将重新加载。 您还将在控制台中看到任何棉绒错误。...

    GitLab Dashboard-crx插件

    语言:English (United States) 该扩展显示了GitLab中所有项目的仪表板 Gitlab Dashboard是一个浏览器扩展,可以帮助使用Gitlab作为版本控制系统的开发人员实时跟踪其项目和分支。 它显示私有(自托管)或公共Gitlab...

    k8s 1.9.2 离线安装,附离线安装包

    在本文中,我们将深入探讨如何在没有互联网连接的环境下安装 Kubernetes (k8s) 版本 1.9.2。这个过程分为几个关键步骤,包括系统准备、环境准备、离线安装和部署 Kubernetes Dashboard。 首先,我们从系统准备开始...

    zabbix-dashboard

    《深入解析Zabbix仪表板与JavaScript技术》 Zabbix是一款强大的网络监控系统,它能够实时监控各种网络设备、服务器性能以及应用服务。其中,Zabbix的仪表板(Dashboard)是其核心功能之一,为管理员提供了直观、...

    Dashboard-Test:演示使用Cypress API进行的UI测试

    2. **cypress/support**: 这里包含了`index.js`和`commands.js`等文件,`index.js`用于引入自定义命令,而`commands.js`则是扩展Cypress内置命令的地方,可以增加一些自定义的功能,以满足项目的特殊需求。...

    KafkaDashboard:仪表板示例,使用Kafka和Spark Streaming汇总日志并更新结果

    Kafka仪表板 这是一个使用Kafka和Spark Streaming来汇总日志并更新结果的仪表板示例。 先决条件: 火花:2.2.1 卡夫卡:1.1.0 Kafka-python:1.4.2 烧瓶:0.12.2 Flask-SocketIO:2.9.6 高图:6.1.0 ...

    GleSYS-CLI-Dashboard:显示glesys服务器的CLI仪表板

    GleSYS CLI仪表板显示GleSYS服务器的CLI仪表板正在安装npm install -g glesys-cli-dashboardglesys-cli-dashboard要求为了使远程日志功能起作用,每个服务器必须满足以下要求: 每个服务器上必须存在具有相同名称和...

    druid-dashboard:可视化Druid查询的UI

    德鲁伊(Druid)是一款高性能、分布式的数据存储和查询引擎,主要用于实时分析和大数据处理。在大数据领域,Druid以其高效的数据加载速度、优秀的查询性能以及对复杂聚合查询的支持而备受关注。...

    dashboard-home:家用仪表板中央服务器

    仪表板家庭服务器家用仪表板中央服务器警告:此存储库包含您可以重用的代码,但该项目对您而言是开箱即用的。 我怀疑您使用与我完全相同的设置,因为它使用了大量的自定义硬件,监视,传感器和自定义内容。...

    paper-dashboard-angular:原始Paper Dashboard的角度版本

    Paper Dashboard Angular是一个Bootstrap管理模板,它结合了柔和的色彩,漂亮的字体和宽敞的卡片和图形。... 它是一个功能强大的仪表板,但重量轻且易于使用。 它具有足够的功能,可以让您完成工作,但是并不拥挤到找不...

    基于Vue3 + Element Plus 的后台管理系统

    基于Vue3 + Element Plus 的后台管理系统解决方案 该方案作为一套多功能的后台框架模板,适用于绝大部分的后台管理系统(Web Management System)开发。基于 Vue3 + pinia,引用 Element Plus 组件库,方便开发快速...

Global site tag (gtag.js) - Google Analytics