Django - 显示来自 SQLite 数据库的图,通过表单访问

Django - Show plot from SQLite database, accessed by form

所以我有一个使用 Django 编写的页面,有人可以在其中将信息输入表单,并在提交时访问 SQLite 数据库以检索查询的信息。到目前为止,我已经做到了这一点,但我无法在页面上的表单下方创建和显示图表。

我尝试了不同的软件包:ChartItGraphosnvd3。无论哪种方式,我都会出错,可能是因为我不了解 Django 中编码的全部细节。

下面是我尝试使用 nvd3 创建绘图。当我尝试加载页面时出现错误:

Exception Value: Invalid block tag: 'load_chart', expected 'elif', 'else' or 'endif'

在我的 viewrun.html 行中,我假设我在 nvd3 中加载:

{% load_chart charttype chartdata "linewithfocuschart_container" True "%d %b %Y %H" %}

这是我使用的文件。感谢您的帮助!

views.py

def createplot(molecules, chemrun_id, database='laminar_idl.test.db'):
    conn, status_db = conn_to_db(database)
    if status_db and not molecules==None:

            time, x, y, abunds, status_fetch = get_one_species_all_times(conn, str(molecules))

            chartdata = {'x': time,
                            'name1': molecules, 'y1': abunds}
            charttype = "lineWithFocusChart"
            data = {
                    'charttype': charttype,
                    'chartdata': chartdata
            }

            return data
    return None

@login_required
def run(request, chemrun_id=1, molecule=None):
    if request.POST:
            form = MolChoiceForm(request.POST)
            if form.is_valid():
                    form.save()
                    molecule = form.cleaned_data['molecule']
                    return HttpResponseRedirect('/chemrun/run/'+chemrun_id+'/'+molecule+'/')
    else:
            form = MolChoiceForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form
    args['chemrun'] = ChemRun.objects.get(id=chemrun_id)

    if not molecule is None:
            args['molecule'] = molecule
            plotdata = createplot(molecule, chemrun_id)
            args['plotdata'] = plotdata

    return render_to_response('interface/viewrun.html', args, context_instance=RequestContext(request))

viewrun.html:

{% extends "interface/base.html" %}

{% block content %}
<article>
    {% if user.is_authenticated %}
        <header>
            <p><font size="+2">Chemical run: <i>{{run.title}}</i> (<b>ID #{{chemrun.id}}</b>)</font></p>
            {% load_chart charttype chartdata "linewithfocuschart_container" True "%d %b %Y %H" %}
        </header>
        <section>
            <p>Outputs written for {{chemrun.n_times}} time steps between {{chemrun.times_min}} and {{chemrun.times_max}} years</p>
            <p>Temperature:                 <b>{{chemrun.temperature}}</p>
            <p>Density:                     <b>{{chemrun.density}}</p>

            <hr>
            <form action='/chemrun/run/{{chemrun.id}}/' method='post' style="display: inline-block;">{% csrf_token %}
                {{form}}
                <input type="submit" name="submit" value="Plot">
            </form>
        </section>
    {% else %}
        <h2>No data available because you are not logged in. 
    {% endif %}
{% endblock %}

base.html:

{% load staticfiles %}
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">

    <link rel="stylesheet" href="{% static 'css/normalize.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/main.css' %}">
    <link media="all" href="{% static 'nvd3/src/nv.d3.css' %}" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src='{% static 'd3/d3.min.js' %}'></script>
    <script type="text/javascript" src='{% static 'nvd3/nv.d3.min.js' %}'></script>
    <!--<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>-->
    <title>Chemicalizer</title>
</head>
<body>
    <div class="header-container">
        <header class="wrapper clearfix">
        <h1 class="title"><b><a href='/'>Chemicalizer</a></b> &nbsp; &nbsp; </h1>
        <!--<h2 class="subtitle">- &nbsp;  &nbsp; You need it!</h2>-->
            <nav>
                <ul>
                    {% if user.is_authenticated %}
                            {% if user.is_superuser %}
                                    <li><a href="/admin/">Admin</a></li>
                                    <li><a href="/chemrun/all/">All Models</a></li>
                            {% else %}
                                    <li><a href="/chemrun/create/">Start model</a></li>
                                    <li><a href="/chemrun/all/">My Models</a></li>
                            {% endif %}
                            <li><a href="/accounts/logout/">Logout</a></li>
                    {% else %}
                            <li><a href="/accounts/login/">Login</a></li>
                            <li><a href="/accounts/register/">Register</a></li>
                            <li><a href="/contact/">Contact</a></li>
                    {% endif %}
                </ul>
            </nav>
        </header>
    </div>
    <div class="main-container">
        <div class="main wrapper clearfix">
                {% block content %}
                {% endblock %}
        </div> <!-- #main -->
    </div> <!-- #main-container -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
    <!--<script src="js/main.js"></script>-->
</body>
</html>

对于未来遇到同样问题的人,我使用的页面没有解释让 nvd3 工作的所有步骤(或者它们可能已经过时)。

以下是安装和运行它的步骤:

1) 使用 pip install django-nvd3

安装 django-nvd3

2) 由于这依赖于python-nvd3,我们需要使用npm install -g bower 安装bower。 (如果你没有 npm,只需使用 macports 或任何其他你喜欢的方式安装它。)

3) 接下来,使用命令 pip install django-bower

安装 django-bower

4) 然后 运行 bower install nvd3 这也将安装依赖项 d3

5) 将您的 view.py 编辑成类似这样的内容,此示例适用于折线图:

charttype = "lineChart"
chartcontainer = 'linechart_container'  # container name
data = {
    'charttype': charttype,
    'chartdata': chartdata,
    'chartcontainer': chartcontainer,
    'extra': {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
        'chart_attr': {
            'xScale':'(d3.scale.log())', #for logscale on x-axis
            'yScale':'(d3.scale.log())', #for logscale on y-axis
            'xAxis.axisLabel':'"Time, yrs"',
            'yAxis.axisLabel':'"n(X)/n(H)"',
        }
    }
}
return data

6) 使用以下内容更新您的 settings.py:

BOWER_COMPONENTS_ROOT = BASE_DIR
BOWER_PATH = '/usr/local/bin/bower'

BOWER_INSTALLED_APPS = (
    'd3',
    'nvd3',
)

同时将 'djangobower.finders.BowerFinder', 添加到您的 STATICFILES_FINDERS = (

7) 现在您的 html 代码必须包含这些(例如在头部):

<link media="all" href="{% static 'nvd3/src/nv.d3.css' %}" type="text/css" rel="stylesheet" />
<script type="text/javascript" src='{% static 'd3/d3.min.js' %}'></script>
<script type="text/javascript" src='{% static 'nvd3/nv.d3.min.js' %}'></script>

在你主体的某处:

{% include_chart_jscss %}
{% load_chart charttype chartdata chartcontainer extra %}

最后,对于你希望剧情出现的地方:

{% include_container chartcontainer %}

这对我有用。如果有更了解这方面的人发现任何错误,请帮助我纠正它们:)