Part 3: Combing Charts.js And Django Rest Framework

in #utopian-io6 years ago (edited)

banner.png

<p dir="auto">This tutorial is part of a series where different aspects of quickly creating and deploying STEEM web applications by using the Django framework as well as Beem are discussed. Knowledge of programming with Python is advised, as well as HTML and CSS. <hr /> <h4>Repository <p dir="auto"><br /><span><a href="https://github.com/chartjs/Chart.js" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">https://github.com/chartjs/Chart.js<span> <a href="https://github.com/django/django" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">https://github.com/django/django <h4>What will I learn <ul> <li>Installing Charts.js and Django Rest Framework <li>Setting up an API endpoint <li>Generating charts with Charts.js <h4>Requirements <ul> <li>Python 3.7 <li>Django 2.1.5 <li>Django Rest Framework 3.9.1 <li>Git <li>Pipenv <h4>Difficulty <ul> <li>intermediate <hr /> <h3>Tutorial <h4>Preface <p dir="auto">The Django framework is quite flexible and can easily be integrated with other frameworks. This allows the programmer to focus on the core functionality while other frameworks can be used for less important features. <h4>Setup <p dir="auto">Download the base files via Github and branch to the initial commit. Install the required packages. <pre><code>$ cd ~/ $ clone https://github.com/Juless89/django-chartsjs.git $ cd django-chartsjs $ pipenv install django==2.1.5 $ pipenv shell (django-chartsjs) $ pip install djangorestframework==3.9.1 (django-chartsjs) $ git fetch origin master b4605e27125712956cf7494d40a529cabd4fc520 (django-chartsjs) $ git checkout b4605e27125712956cf7494d40a529cabd4fc520 <p dir="auto">Run the server, it should look as follow: <pre><code>(django-chartsjs) $ python manage.py runserver <p dir="auto"><center><br /> <img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmabec8urBBUxiBFmaGWbawFLpN8XgUC6tG9e6unibhdqB/Screenshot%202019-02-02%2015.21.42.png" alt="Screenshot 2019-02-02 15.21.42.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmabec8urBBUxiBFmaGWbawFLpN8XgUC6tG9e6unibhdqB/Screenshot%202019-02-02%2015.21.42.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmabec8urBBUxiBFmaGWbawFLpN8XgUC6tG9e6unibhdqB/Screenshot%202019-02-02%2015.21.42.png 2x" /> <h4>Installing Charts.js and Django Rest Framework <p dir="auto">The Django Rest Framework will be used to handle the api calls and needs to be added to <code>settings.py. <pre><code># dashboard/settings.py INSTALLED_APPS = [ . . . 'rest_framework', ] <p dir="auto"><code>Charts.js requires two changes to the <code>base.html script packages. Replace <code>jquery-3.3.1.slim.min.js with the full version and add <code>Chart.bundle.js. <pre><code># templates/base.html <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.js" integrity="sha256-o8aByMEvaNTcBsw94EfRLbBrJBI+c3mjna/j4LrfyJ8=" crossorigin="anonymous"></script> <h4>Setting up an API endpoint <p dir="auto">Create a new view from the class <code>APIView. The view returns data in a JSON format that is compatible with <code>Charts.js. For now the data is hard coded, eventually this should be generated or retrieved from a database. <pre><code># charts/view.py from rest_framework.views import APIView from rest_framework.response import Response class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): data = { "labels": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "data": [12, 19, 3, 5, 2, 3, 10], } return Response(data) <p dir="auto">Register the view to the url <code>api/chart/data/. <pre><code># charts/urls.py from .views import HomePageView, ChartData urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('api/chart/data/', ChartData.as_view()), # new ] <p dir="auto">Validate if the api is working correctly. <a href="http://127.0.0.1:8000/api/chart/data/" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">http://127.0.0.1:8000/api/chart/data/ <p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmS93nECr8PAMinBMrv5BMsjc7mhAXLzjbqSkejoRBuqpy/Screenshot%202019-02-02%2016.10.33.png" alt="Screenshot 2019-02-02 16.10.33.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmS93nECr8PAMinBMrv5BMsjc7mhAXLzjbqSkejoRBuqpy/Screenshot%202019-02-02%2016.10.33.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmS93nECr8PAMinBMrv5BMsjc7mhAXLzjbqSkejoRBuqpy/Screenshot%202019-02-02%2016.10.33.png 2x" /> <h4>Generating charts with Charts.js <p dir="auto">Add the following container to <code>index.html underneath <code><div class="starter-template">. The javascript makes sure the entire block is loaded before the code is run. The html centers the chart and fixes it's size. <pre><code># templates/index.html <div class="container"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6"> <canvas id="myChart" width="400" height="400"> <script> $(document).ready(function(){ {% block jquery %}{% endblock %} }) </script> </canvas> </div> <div class="col-sm-3"></div> </div> </div> <p dir="auto"><code>Charts.js has examples on their website. Which can easily be adjusted. <pre><code><script> var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> <p dir="auto">Create a new file <code>charts.html that extends <code>index.html to separate the code for the chart. Put everything outside the <code><script> tags between: <code>{% block jquery %}....{% endblock %}. Ajax is used to <code>GET the chart data from the <code>api-endpoint and catching any errors. <pre><code>(django-chartsjs) $ touch templates/charts.html # templates/charts.html {% extends 'index.html' %} <script> {% block jquery %} var endpoint = '/api/chart/data' $.ajax({ method: "GET", url: endpoint, success: function(data){ <code for the chart> }, error: function(error_data){ console.log(error_data) } }) {% endblock %} </script> <p dir="auto">Lastly replace <code>labels with <code>data.labels and <code>data with <code>data.data inside the example code from <code>Charts.js. And set the <code>HomePageView to <code>charts.html. <pre><code># templates/charts.html data: { labels: data.labels, #updated datasets: [{ label: 'Votes per day', data: data.data, #updated <pre><code># charts/views.py class HomePageView(View): def get(self, request, *args, **kwargs): return render(request, 'charts.html') <p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmWd18pDMEACLjmLtbKP8ovtBFCW69hvwV6KsSKENSJMh6/Screenshot%202019-02-02%2016.40.14.png" alt="Screenshot 2019-02-02 16.40.14.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmWd18pDMEACLjmLtbKP8ovtBFCW69hvwV6KsSKENSJMh6/Screenshot%202019-02-02%2016.40.14.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmWd18pDMEACLjmLtbKP8ovtBFCW69hvwV6KsSKENSJMh6/Screenshot%202019-02-02%2016.40.14.png 2x" /> <p dir="auto">Changing the type of chart is as easy as changing <code>type, for example to <code>line. Check the website from <a href="https://www.chartjs.org/" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Charts.js for an overview of all possible charts. <p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmbk5xuFoKwJbcZ2s2zstHL8xZAxdKcrbVRmSetcbohKNK/Screenshot%202019-02-02%2016.40.34.png" alt="Screenshot 2019-02-02 16.40.34.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmbk5xuFoKwJbcZ2s2zstHL8xZAxdKcrbVRmSetcbohKNK/Screenshot%202019-02-02%2016.40.34.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmbk5xuFoKwJbcZ2s2zstHL8xZAxdKcrbVRmSetcbohKNK/Screenshot%202019-02-02%2016.40.34.png 2x" /> <h3>Curriculum <ul> <li><a href="https://steemit.com/@steempytutorials/part-0-create-steem-web-applications-with-django-and-steem-python" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 0: Create STEEM web applications with Django and Steem-Python <li><a href="https://steemit.com/utopian-io/@steempytutorials/part-1-using-the-url-to-dynamically-pull-data-via-the-steem-api-and-parse-to-html" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 1: Using the URL to dynamically pull data via the Steem API and parse to html <li><a href="https://steemit.com/utopian-io/@steempytutorials/part-2-using-a-bootstrap-template-to-parse-steem-posts-via-beem-api" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 2: Using A Bootstrap Template To Parse STEEM Posts Via Beem API <hr /> <p dir="auto">The code for this tutorial can be found on <a href="https://github.com/Juless89/django-chartsjs" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Github! <p dir="auto"><span>This tutorial was written by <a href="/@juliank">@juliank.
Sort:  


After analyzing your tutorial we suggest the following:Thank you for your contribution @steempytutorials.

  • We suggest you enter comments in the sections of your code. The comments in the code greatly help users understand what you are developing.

  • In your tutorial it would be important to have more theory about the concepts and librarias you are using. It could explain what APIView is and why it will use it. It could also explain what Charts.js is like other concepts it used in its contribution.

  • Further detail your tutorial, always think that you are explaining a subject that can appear non-experienced readers on this subject and experienced readers in order to encompass for all readers.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thanks for the feedback

Thank you for your review, @portugalcoin! Keep up the good work!

Nice work again.

When I was using ChartJS, I didn't make use of a the rest-framework. This looks much easier than the way I got it working. More extensible too!

Thanks! I agree that it is super extensible, this is just a simple introduction. You can pull all the chart settings from a database and play around with the URL path even more. For example: /api/chart/data/<slug:type>/ for different charts.

Hi @steempytutorials!



Feel free to join our @steem-ua Discord serverYour post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation! Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!

Hey, @steempytutorials!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
SteemPlus or Steeditor). Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!