Django - Show plot from SQLite database, accessed by form

主宰稳场 提交于 2019-12-25 06:58:49

问题


So I have a page written using Django where someone can enter information into a form, and on submit it accesses a SQLite database to retrieve the queried information. So far I have gotten this far, but I am not able to create and show a plot below the form on the page.

I have tried different packages: ChartIt, Graphos and nvd3. Either way I get an error, likely because I don't understand the full details of the coding in Django.

Below is my try at creating a plot with nvd3. When I try to load the page I get the error:

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

at the line in my viewrun.html where I assume I load in the nvd3:

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

Here are the files I use. Thank you for any help!

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>

回答1:


For people in the future fighting the same problem, I was using pages that did not explain all steps for getting nvd3 to work (or they were maybe outdated).

Here are the steps to follow to install it and get it working:

1) Install django-nvd3 using pip install django-nvd3

2) Since this is dependent on python-nvd3, we need to install bower using npm install -g bower. (If you don't have npm, just install it with macports, or any other way you like.)

3) Next, install django-bower with the command pip install django-bower

4) Then run bower install nvd3 which will also install the dependency d3

5) Edit your view.py to something like this, this example is for a lineChart:

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) Update your settings.py with the following:

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

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

and also add 'djangobower.finders.BowerFinder', to your STATICFILES_FINDERS = (

7) Now your html code has to include these (in the head for example):

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

And somewhere in your main body:

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

Finally, for wherever you want the plot to appear:

{% include_container chartcontainer %}

This worked for me. If anyone more knowledgeable about this finds any mistakes, please help me correct them :)



来源:https://stackoverflow.com/questions/31637980/django-show-plot-from-sqlite-database-accessed-by-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!