Git Product home page Git Product logo

django-chartit's Introduction

Django-Chartit

Documentation Status

image

Code Health

image

Django Chartit is a Django app that can be used to easily create charts from the data in your database. The charts are rendered using Highcharts and jQuery JavaScript libraries. Data in your database can be plotted as simple line charts, column charts, area charts, scatter plots, and many more chart types. Data can also be plotted as Pivot Charts where the data is grouped and/or pivoted by specific column(s).

Changelog

  • master
    • Update demo with an example of how to pass legendIndex as an option to a data serie. Closes #48.
    • Update demo with an example of how to change the label of any term instead of using the default one. Closes #46.
  • 0.2.9 (January 17, 2017)
    • Enable pylint during testing but don't block Travis-CI on failures. Closes #42.
    • Handle unicode data in pie and scatter plot charts under Python 2.7. PR#47.
  • 0.2.8 (December 4, 2016)
    • PivotChart and PivotDataPool will be deprecated soon. Both are marked with deprecation warnings. There is a lot of duplication and special handling between those classes and the Chart and DataPool classes which make it harder to expand the feature set for django-chartit. The next release will focus on consolidating all the functionality into Chart and DataPool so that users will still be able to draw pivot charts. You will have to construct your pivot charts manually though!
    • DataPool terms now supports model properties. Fixes #35. Model properties are not supported for PivotDataPool! WARNING: when using model properties chartit can't make use of ``QuerySet.values()`` internally. This means results will not be groupped by the values of the fields you supplied. This may lead to unexpected query results/charts!
    • DataPool now supports RawQuerySet as data source. Fixes #44. RawQuerySet is not supported for PivotDataPool! WARNING: when using ``RawQuerySet`` don't use double underscores in field names because these are interpreted internally by chartit and will cause exceptions. For example don't do this ``SELECT AVG(rating) as rating__avg`` instead write it as ``SELECT AVG(rating) as rating_avg``!
    • README now tells how to execute demoproject/
  • 0.2.7 (September 14, 2016)
    • Don't use super(self.__class__) b/c that breaks chart class inheritance. Fixes #41
  • 0.2.6 (August 16, 2016)
    • Merge chartit_tests/ with demoproject/
    • Load test DB with real data to use during testing
    • Add more tests
    • Update the path to demoproject.settings when building docs. Fixes a problem which caused some API docs to be empty
    • Fix ValueError: not enough values to unpack (expected 2, got 0) with PivotChart when the QuerySet returns empty data
    • Dropped requirement on simplejson
    • Properly handle unicode data in Pivot charts. Fixes #5
    • Demo project updated with Chart and PivotChart examples of rendering DateField values on the X axis
    • Allow charting of extra() or annotate() fields. Fixes #8 and #12
    • Refactor RecursiveDefaultDict to allow chart objects to be serialized to/from cache. Fixes #10
    • Add information about supported 3rd party JavaScript versions. Fixes #14
  • 0.2.5 (August 3, 2016)
    • Workaround Python 3 vs. Python 2 list sort issue which breaks charts with multiple data sources displayed on the same axis!
    • Make demoproject/ compatible with Django 1.10
  • 0.2.4 (August 2, 2016)
    • Fix for get_all_field_names() and get_field_by_name() removal in Django 1.10. Fixes #39
    • Updated for django.db.sql.query.Query.aggregates removal
  • 0.2.3 (July 30, 2016)
    • New to_json() method for charts. Useful for creating Highcharts in AJAX
    • Merged with django-chartit2 fork by Grant McConnaughey which adds Python 3 and latest Django 1.8.x and 1.9.x support
    • Allow dictionary fields in conjunction with lambda fields. Closes #26
    • Documentation improvements
    • Lots of code cleanups and style improvements
  • 0.2.2 as django-chartit2 (January 28, 2016)
    • Fixed another issue that prevented installation via PyPI
  • 0.2.0 as django-chartit2 (January 20, 2016):
    • Fixed issue that could prevent installation via PyPI
  • 0.1 (November 5, 2011)
    • Initial release of django-chartit

Features

  • Plot charts from models.
  • Plot data from multiple models on the same axis on a chart.
  • Plot pivot charts from models. Data can be pivoted by across multiple columns.
  • Legend pivot charts by multiple columns.
  • Combine data from multiple models to plot on same pivot charts.
  • Plot a pareto chart, paretoed by a specific column.
  • Plot only a top few items per category in a pivot chart.
  • Python 3 compatibility
  • Django 1.8 and 1.9 compatibility
  • Documentation to ReadTheDocs
  • Automated testing via Travis CI
  • Test coverage tracking via Coveralls

Installation

You can install Django-Chartit from PyPI. Just do :

$ pip install django_chartit

Then, add chartit to INSTALLED_APPS in "settings.py".

You also need supporting JavaScript libraries. See the Required JavaScript Libraries section for more details.

How to Use

Plotting a chart or pivot chart on a webpage involves the following steps.

  1. Create a DataPool or PivotDataPool object that specifies what data you need to retrieve and from where.
  2. Create a Chart or PivotChart object to plot the data in the DataPool or PivotDataPool respectively.
  3. Return the Chart/PivotChart object from a django view function to the django template.
  4. Use the load_charts template tag to load the charts to HTML tags with specific ids.

It is easier to explain the steps above with examples. So read on.

How to Create Charts

Here is a short example of how to create a line chart. Let's say we have a simple model with 3 fields - one for month and two for temperatures of Boston and Houston. :

class MonthlyWeatherByCity(models.Model):
    month = models.IntegerField()
    boston_temp = models.DecimalField(max_digits=5, decimal_places=1)
    houston_temp = models.DecimalField(max_digits=5, decimal_places=1)

And let's say we want to create a simple line chart of month on the x-axis and the temperatures of the two cities on the y-axis. :

from chartit import DataPool, Chart

def weather_chart_view(request):
    #Step 1: Create a DataPool with the data we want to retrieve.
    weatherdata = \
        DataPool(
           series=
            [{'options': {
               'source': MonthlyWeatherByCity.objects.all()},
              'terms': [
                'month',
                'houston_temp',
                'boston_temp']}
             ])

    #Step 2: Create the Chart object
    cht = Chart(
            datasource = weatherdata,
            series_options =
              [{'options':{
                  'type': 'line',
                  'stacking': False},
                'terms':{
                  'month': [
                    'boston_temp',
                    'houston_temp']
                  }}],
            chart_options =
              {'title': {
                   'text': 'Weather Data of Boston and Houston'},
               'xAxis': {
                    'title': {
                       'text': 'Month number'}}})

    #Step 3: Send the chart object to the template.
    return render_to_response({'weatherchart': cht})

And you can use the load_charts filter in the django template to render the chart. :

<head>
    <!-- code to include the highcharts and jQuery libraries goes here -->
    <!-- load_charts filter takes a comma-separated list of id's where -->
    <!-- the charts need to be rendered to                             -->
    {% load chartit %}
    {{ weatherchart|load_charts:"container" }}
</head>
<body>
    <div id='container'> Chart will be rendered here </div>
</body>

How to Create Pivot Charts

Here is an example of how to create a pivot chart. Let's say we have the following model. :

class DailyWeather(models.Model):
    month = models.IntegerField()
    day = models.IntegerField()
    temperature = models.DecimalField(max_digits=5, decimal_places=1)
    rainfall = models.DecimalField(max_digits=5, decimal_places=1)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)

We want to plot a pivot chart of month (along the x-axis) versus the average rainfall (along the y-axis) of the top 3 cities with highest average rainfall in each month. :

from django.db.models import Avg
from chartit import PivotDataPool, PivotChart

def rainfall_pivot_chart_view(request):
    # Step 1: Create a PivotDataPool with the data we want to retrieve.
    rainpivotdata = PivotDataPool(
        series=[{
            'options': {
                'source': DailyWeather.objects.all(),
                'categories': ['month'],
                'legend_by': 'city',
                'top_n_per_cat': 3,
            },
            'terms': {
                'avg_rain': Avg('rainfall'),
            }
        }]
    )

    # Step 2: Create the PivotChart object
    rainpivcht = PivotChart(
        datasource=rainpivotdata,
        series_options=[{
            'options': {
                'type': 'column',
                'stacking': True
            },
            'terms': ['avg_rain']
        }],
        chart_options={
            'title': {
                'text': 'Rain by Month in top 3 cities'
            },
            'xAxis': {
                'title': {
                    'text': 'Month'
                }
            }
        }
    )

    # Step 3: Send the PivotChart object to the template.
    return render_to_response({'rainpivchart': rainpivcht})

And you can use the load_charts filter in the django template to render the chart. :

<head>
    <!-- code to include the highcharts and jQuery libraries goes here -->
    <!-- load_charts filter takes a comma-separated list of id's where -->
    <!-- the charts need to be rendered to                             -->
    {% load chartit %}
    {{ rainpivchart|load_charts:"container" }}
</head>
<body>
    <div id='container'> Chart will be rendered here </div>
</body>

Rendering multiple charts

It is possible to render multiple charts in the same template. The first argument to load_charts is the Chart object or a list of Chart objects, and the second is a comma separated list of HTML IDs where the charts will be rendered.

When calling Django's render you have to pass all you charts as a list:

return render(request, 'index.html',
             {
                'chart_list' : [chart_1, chart_2],
             }
        )

Then in your template you have to use the proper syntax:

<head>
    {% load chartit %}
    {{ chart_list|load_charts:"chart_1,chart_2" }}
</head>
<body>
    <div id="chart_1">First chart will be rendered here</div>
    <div id="chart_2">Second chart will be rendered here</div>
</body>

Demo

The above examples are just a brief taste of what you can do with Django-Chartit. For more examples and to look at the charts in actions, check out the demoproject/ directory. To execute the demo run the commands :

cd demoproject/
PYTHONPATH=../ python ./manage.py migrate
PYTHONPATH=../ python ./manage.py runserver

Documentation

Full documentation is available here .

Required JavaScript Libraries

The following JavaScript Libraries are required for using Django-Chartit.

  • jQuery - versions 1.6.4 and 1.7 are known to work well with django-chartit.
  • Highcharts - versions 2.1.7 and 2.2.0 are known to work well with django-chartit.

Note

While Django-Chartit itself is licensed under the BSD license, Highcharts is licensed under the Highcharts license and jQuery is licensed under both MIT License and GNU General Public License (GPL) Version 2. It is your own responsibility to abide by respective licenses when downloading and using the supporting JavaScript libraries.

django-chartit's People

Contributors

atodorov avatar cajbecu avatar elmkarami avatar grantmcconnaughey avatar jonpeel avatar miaekim avatar mpena2099 avatar pgollakota avatar sramana avatar tahv0 avatar u-238 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-chartit's Issues

RFE: Support for list sources

From the example docs:

    weatherdata = \
        DataPool(
           series=
            [{'options': {
               'source': MonthlyWeatherByCity.objects.all()},
              'terms': [
                'month',
                'houston_temp',
                'boston_temp']}
             ])

I'm storing some data in Amazon SImpleDB and retrieving / working with it as lists of dictionary objects. At present it is not possible to use these lists for the source parameter in Django charts. Please add support for that (i.e. do not require QuerySet, Manager or a Model.

highcharts formatter

Hello! I'm sorry if this isn't the place to ask, but I wanted to know if chartit supports passing formatter javascript functions to the chart, and if so, how to do so.

I have a two-level donut chart that retrieves data from the database, where each data object carries two distinct numeric values. I'm charting them together on the donut's outer layer with their total in the inner layer, but there's a lot of 0 values clustering at the top of the outer chart (which may, by the way, mean I'm not doing the drilldown right.) Since each zero value may be paired with a non zero value in their data objects, I can't straight up exclude them from the queryset. Google says to use a formatter function in HighCharts that checks the value and returns it only if it's greater than 0:

dataLabels: { formatter:function() { if(this.y != 0) { return this.y; } } }

Problem is, attempting to pass such a function as is conflicts with Python interpretation, and passing it as a string seems to erase the whole chart.

So, yeah, is there a way to pass functions as of now? And if not, can you guys help me figure out what to do?

Cannot enable 3d rendering

i am trying to activate 3r rendering to make a 3d pie chart... there is no documentation that says how can that be done.

Generate Charts from Views?

I'm going through the documentation but I'm a bit confused on one thing. On all the examples charts are generated from data on models.

I'm using an API (in my views.py) to retrieve data and I would like to generate charts on the fly without the need to save this data to my db. Is this possible? Any example that uses data from the views?

Thanks

can't import six

Hey, i'm having troubles when i try to work my django project because of six dependency. Is there any suggestions to solve this issue? This is the error:
ImportError: cannot import name 'six' from 'django.utils'

column chart data is being sorted by y-axis values

Hello,

I'm trying to figure out why my QuerySet is being re-ordered when plotted via chartit. The data set is filtered() and then order_by() is called. I've verified the output of those calls is as expected.

However, when I examine the output produced after the django templating creates the source HTML, the series is re-ordered in the HTML file.

I tried to reproduce it using highcharts without chartit in between, but it seems that chartit is re-ordering the QuerySet?

Is this something that can be disabled during the Chart call, or is this the expected behavior of the function?

Sorry if this is a silly question, but I can't find any documentation referencing this behavior in chartit or highcharts.

Regards,
Dan

Series order is not preserved

The order of the series is not preserved, series appear in a random order in the chart.
Series should be assigned to the chart in the order either given in the data pool or in the 'terms' statement.

I haven't looked at the code, but I guess at some stage the ordering is redone by subjecting it to a dict or set.

The use of 'use_decimal' assumes simplejson

In the template tag load_charts on line 70 there is use_decimals=True in dumps(). The library uses django's simplejson which gracefully falls back to python's built in json lib which does not have a use_decimals argument to its dumps().

Support for datetime objects in xAxis

Hi.

I've read that support for datetime objects is going to be a feature of the next release. Right now it's kinda critical for me. What's your advance on it? Should I try to do it?

cache.get entire Chart object fails

    chart = Chart(
            datasource = metricsdata,
            series_options = [
                {'options': {
                        'type': 'line',
                        'stacking': False,
                    },
                    'terms': chart_terms
                }
            ],
            chart_options = {
                'title': { 'text': 'Metrics - Last 30 days'},
                'xAxis': { 'title': {'text': 'Date'}},
                'yAxis': { 'title': {'text': 'Count'}},
            }
        )

cache.set works fine.

cache.get OTOH:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/lib/python2.6/site-packages/s3cache/__init__.py", line 98, in get
    return pickle.load(f)
  File "lib/python2.6/site-packages/chartit/utils.py", line 24, in __init__
    self.update(self.data)
  File "lib/python2.6/site-packages/chartit/utils.py", line 40, in update
TypeError: ("descriptor 'keys' of 'dict' object needs an argument", <class 'chartit.highcharts.hcoptions.HCOptions'>, (<class 'chartit.highcharts.hcoptions.HCOptions'>,))

Where s3cache is a custom cache backend (https://github.com/atodorov/django-s3-cache) similar to the filesystem cache backend but stores data in Amazon S3.

Chart series_options & Customize plot

A French guy

Hello, I'm studying on Chartit and I have questions.

I want to know how customize my plots (color by example and others).

This is my code

        series_options =
           [{'options':{
              'type': 'line'},
              'xAxis': 0,
              'yAxis': 0,
              'zIndex': 1,

            'terms': {
              'month': [
                'boston_temp']}},
            {'options': {
                'type': 'column',
                'xAxis': 1,
                'yAxis': 1},

            'terms': {
                'month': [
                    'houston_temp']}}],

Thank you

support for QuerySet.annotate()

It seems using QuerySet.annotate() breaks chartit. the problem lies at validation.py:30 where it validates that the fields used are part of the model. meta.get_all_field_names() doesn't return annotated fields, for instance a Count() or an Avg() which are very useful in the case of a chart.
here's the offending code:

    model_fields = model._meta.get_all_field_names()
    if terms[0] not in model_fields:
        raise APIInputError("Field %r does not exist. Valid lookups are %s."
                         % (terms[0], ', '.join(model_fields)))
    if len(terms) == 1:
            return model._meta.get_field(terms[0]).verbose_name

as a temporary fix I changed it to this but it's just a dirty workarround and effectively breaks the validation:

    model_fields = model._meta.get_all_field_names()
    if terms[0] not in model_fields:
        pass
    if len(terms) == 1:
        try:
            return model._meta.get_field(terms[0]).verbose_name
        except:
            return str(terms[0])

time series data

Hi,

When I try to graph my time series data, 1 data point a day, I noticed where there are no data during the weekend, the days are now show, but rather skipped. I would like to keep these days showing '0'. It seems I shall either set 'xAxis': {'type': 'datetime'}, or 'xAxis': {'ordinal': 'false'}. Neither seem to work. Especially, having 'type':'datetime' does not seem to have an effect. Can you please help?

Thanks,

ignore

Is django-chartit a dead package? There has been some development in the last 6 months or so, but there hasn't been an update to PyPI for 4 years. If this is no longer actively maintained, can someone else be allowed to pull changes into the project and submit updates to PyPI?

django.utils.six

Hi, you are using six modules not compatible with django 3
one import broke my site, and I managed to fix it,

it's in chartit/templatetags/chartit.py,

import itertools instead of six, and change line 84:

for hco, render_to in six.zip_longest(

for hco, render_to in itertools.zip_longest(

Checks only the model fields/fails with extra fields in the query set

Hi,
I got this error:

chartit/validation.py" in _validate_field_lookup_term
  32.                          % (terms[0], ', '.join(model_fields)))

Exception Type: APIInputError at /..../
Exception Value: Field 'added' does not exist. Valid lookups are comment, id, key, metric, milestone, when_added.

The relevant code is:

metricsdata = DataPool(
        series= [{'options': { 'source': InternalTimedMetrics.objects.extra(select={'added': "DATE_FORMAT(when_added,'%Y-%m-%d')"}).filter(key=METRIC_APPS_ACTIVE) },
                'terms': [ 'metric', 'added']
                }
            ]
        )

#Step 2: Create the Chart object
cht = Chart(
        datasource = metricsdata,
        series_options =
          [{'options':{
              'type': 'line',
              'stacking': False},
            'terms':{
              'added': ['metric']
              }}]
        )

I'm trying to workaround the fact that datetime is not supported for X axis by converting the values to string right in the DB layer but your sanity checks got me.

Chartit error when added to INSTALLED_APPS

I have Python33 with Django-1.6.5. When chartit is added to INSTALLED_APPS I got error.

Scenario:
django-admin.py startproject testpage
cd testpage
edit settings.py and add 'chartit', to INSTALLED_APPS

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'chartit',
)

python manage.py runserver

Validating models...

0 errors found
June 18, 2014 - 11:14:33
Django version 1.6.5, using settings 'testpage.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\core\management
init.py", line 399, in execute_from_command_line
utility.execute()
File "C:\Program Files (x86)\Python33\lib\site-packages\django\core\management
init.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\core\management
\base.py", line 242, in run_from_argv
self.execute(args, *options.dict)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\core\management
\base.py", line 280, in execute
translation.activate('en-us')
File "C:\Program Files (x86)\Python33\lib\site-packages\django\utils\translati
on__init
.py", line 130, in activate
return _trans.activate(language)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\utils\translati
on\trans_real.py", line 188, in activate
_active.value = translation(language)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\utils\translati
on\trans_real.py", line 177, in translation
default_translation = fetch(settings.LANGUAGE_CODE)
File "C:\Program Files (x86)\Python33\lib\site-packages\django\utils\translati
on\trans_real.py", line 159, in fetch
app = import_module(appname)
File "C:\Program Files (x86)\Python33\lib\importlib__init
.py", line 90, in
import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1584, in _gcd_import
File "", line 1565, in _find_and_load
File "", line 1532, in _find_and_load_unlocked
File "", line 584, in _check_name_wrapper
File "", line 1022, in load_module
File "", line 1003, in load_module
File "", line 560, in module_for_loader_wrapper
File "", line 868, in load_module
File "", line 313, in call_with_frames_removed
File "C:\Program Files (x86)\Python33\lib\site-packages\django_chartit-0.1-py3
.3.egg\chartit__init
.py", line 3, in
from .chartdata import PivotDataPool, DataPool
File "C:\Program Files (x86)\Python33\lib\site-packages\django_chartit-0.1-py3
.3.egg\chartit\chartdata.py", line 109
sort_grp_fn = lambda (tk, td): tuple(chain(str(td['source'].query),
^
SyntaxError: invalid syntax

'Graph' object has no attribute 'META'

While making a CBV for my model. I am getting the following error : 'Graph' object has no attribute 'META'

:

here is my view
::

class Graph(TemplateView):

    def get(request, *args, **kwargs):
        template_name = "base.html"
        peoplecount = DataPool(
            series=[{'options': {
                    'source': PeopleCount.objects.all()},
                'terms': [
                    'timestamp',
                    'people_count_left',
                    'people_count_right']}
                    ])

        cht = Chart(
            datasource=peoplecount,
            series_options=[{'options': {
                'type': 'line',
                'stacking': False},
                'terms': {
                'timestamp': [
                    'people_count_left',
                    'people_count_right']
            }}],
            chart_options={'title': {
                'text': 'People Count'},
                'xAxis': {
                'title': {
                    'text': 'People Count'}}})

        return render(request, template_name, {'peoplecount': cht})

Any pointers for this?

Unicode errors

I'm getting "UnicodeEncodeError" from chartit.

'ascii' codec can't encode character u'\u2013' in position 33: ordinal not in range(128)
Django Version: 1.4
Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode character u'\u2013' in position 33: ordinal not in range(128)
Exception Location: /lib/python2.6/site-packages/chartit/chartdata.py in _get_data, line 525
Python Version: 2.6.5

This specifically seems related to "lv = tuple(map(str, lv))", when "lv" contains an en-dash. I suspect I'll get even more of these errors on my data since I can't reasonably force all of my data into ASCII.

Hopefully you can check your code over for this and related issues. If I have the time, I'll try and fix this and send my solution on, but for now I'm forced to work around this.

Order by y-axis field

Hi,

I am using django-chartit to display a site name on x-axis and its response time on y-axis.
How do I sort the graph with the response time in ascending order.

Below is my code :

siteresppivotdata = PivotDataPool(
       series =
        [{'options': {
           'source': MonthlySiteResponse.objects.all().order_by('response_time'),
           'categories': ['site_name', ],
           'legend_by' : ['site_name'],
           },
          'terms': {
            'total_response_time': Avg('response_time')}}
         ],
       )

#Step 2: Create the PivotChart object
siteresppivcht = PivotChart(
        datasource = siteresppivotdata,
        series_options =
          [{'options':{
              'type': 'column',
              'stacking': True},
            'terms':[
              'total_response_time']}],
           chart_options =
          {'title': {
               'text': 'Monthly Site Response Time'},
           'xAxis': {
                'title': {
                   'text': 'Website'}},
           'yAxis': {
                'title': {
                   'text': 'Response Time'}}}
        )

Also is there a way to show the graph vice-versa (i.e site name on y-axis and response-time on x-axis)

setting legend order

I would like to have the legends in an alphabetical order. It looks like HighChart allows using legendIndex in series to set order. How do I pass this on with chartit? Thanks

series: [{
        name: 'base',
        data: [10, 20, 30],
        index: 1,
        legendIndex: 0
    },
    {
        name: 'sec',
        data: [30, 20, 10],
        index: 0,
        legendIndex: 1
    }
]

RFE: Drop simplejson dependency

In #32 there's a patch which drops the simplejson dependency entirely and replaces it with the standard json module. Need to take a look at this and make some tests but sounds like a good idea.

Exception Value: __init__() got an unexpected keyword argument 'use_decimal'

Hi, I ve got a very strange issue: When i load my application without a virtual environment, everything is fine. If I load it within a virtual environment with exactly the same conf or on another machine, i get the following exception:

Exception Value:

init() got an unexpected keyword argument 'use_decimal'

Exception Location: /usr/lib/python2.7/json/init.py in dumps, line 240
Python Executable: /home/ilya/virtenv/bin/python

The renderer gets a problem in line 7:

init() got an unexpected keyword argument 'use_decimal'
...
7 {{cht|load_charts:"chart"}}
...

The stackTrace goes to

/home/ilya/projects/virtenv/local/lib/python2.7/site-packages/chartit/templatetags/chartit.py in load_charts

                                                         use_decimal=True),

...

▶ Local vars
/usr/lib/python2.7/json/init.py in dumps

        **kw).encode(obj)

...

In my original environment as in my virtual environment, all the packages were installed using pip. Any Idea?

Thanks, Ilya

'Options' object has no attribute 'get_all_field_names'

Hi, got an error ('Options' object has no attribute 'get_all_field_names')
I use Django 1.10 + Python 3.5
See traceback below.

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/event/9140/

Django Version: 1.10.1
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djcelery',
'registration',
'ckeditor',
'gunicorn',
'chartit',
'app',
'paymentbackend']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/alex/Python-scripts/ticketa/app/views.py" in single_event
187. "price", "date_data_collected"]}])

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/chartit/chartdata.py" in init
89. self.series = clean_dps(series)

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/chartit/validation.py" in clean_dps
295. clean_dps(series)

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/chartit/validation.py" in clean_dps
288. fa = _validate_field_lookup_term(td['source'].model, td['field'])

File "/Users/alex/virtualenvs/ticket_venv/lib/python3.5/site-packages/chartit/validation.py" in _validate_field_lookup_term
30. model_fields = model._meta.get_all_field_names()

Exception Type: AttributeError at /event/9140/
Exception Value: 'Options' object has no attribute 'get_all_field_names'

Specify third-party apps versions on documentation

There is no reference to third-party apps versions on documentation. I spent a bit of time trying workable ones of:

  • jQuery
  • Highcharts

It will be nice to put Django's tested versions too.

In my case, I'm using jQuery 1.7, highcharts 2.2.0 and Django 1.4.3 (latest).

'NoneType' object is not subscriptable

'NoneType' object is not subscriptable

Exception Value: 'NoneType' object is not subscriptable
C:\Python36\lib\site-packages\chartit\templatetags\chartit.py in load_charts, line 86

__proxy__ found error if translated field supplied as "legend_by"

lgby_titles = (':'.join(lgby_vname_list).title() for

This line causing "sequence item 0: expected str instance, proxy found" error if a translated field is found.```


        lgby_titles = []
        for lgby_vname_list in lgby_vname_lists:
            tmp_list = (str(vname).title() for vname in lgby_vname_list)
            lgby_titles.append(':'.join(tmp_list))

if wrote like above, no errors. Its identical, but this list yields proxy fields for translated fields if wrote as original.

Support for RawQuerySet

Is this possible? Sometimes the ORM just can't do what I need and a raw query is the easiest way to go.

Can't use model properties in chartit

Hi everyone!

I tried to use chartit with a property in my model but then I get a "Field XYZ does not exist. Valid lookups are ..."

The main problem I wanted to solve was to format the date from the database for the x-Axis in a specific manner. Maybe there is another solution for this which I cant figure out at the moment? I already tried to use js options of chartit to reformat the date like documented here http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/xaxis/datetimelabelformats/ but it seems as these options are only working on js date data and not with strings from the database...

Uncaught ReferenceError: $ is not defined at chartloader.js:3

Greetings,

I am facing an odd error described in the title when I attempt to integrate django-chartit into my project.

Many solutions told to import jQuery above all other libraries, but it turns out it is since the creation of my project:

<script type="text/javascript" src="{% static "js/jquery.js" %}"></script>
<script type="text/javascript" src="{% static "js/bootstrap.js" %}"></script>
<script type="text/javascript" src="{% static "js/highcharts.js" %}"></script>

I've also tried to manually edit the chartloader.js file, by changing $ to jQuery, but the error continues, except saying jQuery is not defined.

Cannot zoom data series

This is my data series:
var _chartit_hco_array = [{"series": [{"stacking": false, "zoomType": "x", "type": "line", "name": "cell_7", "data": [10.586, 10.981, 12.433, 13.537, 11.149000000000001, 12.506, 12.504, 11.191]}]

Does Chartit support zooming or is it something wrong with my data? Please have a look guys. Thanks.

Multiple charts

Hi,

as I cannot find a mailing list or support email,
how can you get multiple charts in different containers? I mean, how can you use the local_charts filter for multiple charts? is it possible at all?

{{ linechart|load_charts:"container"}}

using two calls

{{ linechart|load_charts:"container1"}}
{{ barchart|load_charts:"container2"}}

did not work

regards,

Albertos

Change series label on line charts

Hi! In the example:

cht = Chart(
        datasource = ds, 
        series_options = 
          [{'options':{
              'type': 'line',
              'stacking': False},
            'terms':{
              'month': [
                'boston_temp',
                'houston_temp']
              }}],
        chart_options = 
          {'title': {
               'text': 'Weather Data of Boston and Houston'},
           'xAxis': {
                'title': {
                   'text': 'Month number'}}})

How could I change the series name? I do not want to use "Boston Temp" and "Houston Temp" automatically...

Thanks!
Mauricio

settings.py missing from the documentation

I know it's probably obvious to any seasoned django dev but chartit's install documentation doesn't mention the fact that you need to add 'chartit' to your settings.py's INSTALLED_APPS list.

made me curse for 10minutes before I figured it out. and also, now I feel dumb.

'chartit' is not a valid tag library: ImportError raised loading chartit.templatetags.chartit: cannot import name simplejson

I received the following error:

'chartit' is not a valid tag library: ImportError raised loading chartit.templatetags.chartit: cannot import name simplejson
Exception Type: TemplateSyntaxError

Django version 1.8.5. Python version 2.7.5.

I saw this, and making the changes did not work: http://stackoverflow.com/questions/23564529/chartit-is-not-a-valid-tag-librarydjango . When making that change, django then complains about: 'NoneType' object has no attribute 'getitem' with the line: {{ alertchart|load_charts:"container" }}

It simply complains about " {% load chartit %}".

get_all_field_names deprecated in newest Django update

Copy of grantmcconnaughey#7 as I'm merging the two projects:

@dylanfetch commented 16 days ago:

chartit\validation.py:30: RemovedInDjango110Warning: 'get_all_field_names is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()'
model_fields = model._meta.get_all_field_names()

I got this error while displaying a 2 axis line graph.

@grantmcconnaughey commented 16 days ago

Does it raise an exception or just print out a warning? This library is not compatible with Django 1.10 yet since it isn't released yet.

@dylanfetch commented 12 days ago • edited

It's just the warning I think. That message is displayed on the log and the
border and titles of the graph are displayed, but the plot is not. Sorry if
I didn't provide enough information, I've never opened an issue on a
project before. I was unaware that I moved to an unreleased version of
Django. I updated recently while trying to resolve an issue I was having
migrating. I'll try to move back to the previous version.

Edit: I just checked and I'm using Django 1.9.7

Thank you,
Dylan Fetch

Themes

Is there any way to apply a new theme from highchart ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.