0

I'm trying get user input from a HTML form and use that value to populate a ChartJS graph in my Django app called DisplayData which has a template called Display.html. I have an API set up to pass data into ChartJS called display/api/chart/data/ which I use to get two lists to populate the Chart with. In order make the Chart, I am getting data from my models and graphing the data value (integer) against the timestamp of when the value of recorded. This is one of the queries that gets the data:

all_entries = models.Entries.objects.all().filter(parent=2)

Right now, I have it hardcoded to one time of data value (as seen above, to the integer 2), but I would like the user to have a form where they can input a number and submit it, generating the chart by using that integer as a filter. The user input integer would be placed inside the parent= portion of the code above.

I have the following urls set up.

urls.py

urlpatterns=[
    url(r'^$',views.DisplayView, name='DisplayView'),
    url(r'^api/data/$', views.get_data, name='api-data'),
    url(r'^display/api/chart/data/$', views.ChartData.as_view()),
    url(r'^logs/', views.LogDisplay, name='Display-Logs'),
]

In order to achieve this, I have added a form in my Display.html file above the code for ChartJs as follows.

Display.html

{% block content %}

<div class="row">
    <h4>Enter measurable number:</h4>
    <form method="POST">
        {% csrf_token %}
        <input type="number" name="textfield">
        <button type="submit">Submit</button>
    </form>
</div>


<div class='padded'>
    <div class='col-sm-12' url-endpoint='{% url "api-data" %}'>
        <h1>Graph Data</h1>
        <canvas id="myChart" width="400" height="400"></canvas>
    </div>  
</div>

<script>
{% block jquery %}
var endpoint = 'display/api/chart/data/'
var defaultData = []
var defaultLabels = [];
$.ajax({
    method: "GET",
    url: endpoint,
    success: function(data){
        defaultLabels = data.labels
        defaultData = data.default
        console.log(data)
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: defaultLabels,
                datasets: [{
                    label: '# Measurable',
                    data: defaultData,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
})

{% endblock %}

</script>

{% endblock %}

The first part of the code is the form to get data from the user, the second part is the code to generate the graph which we can ignore right now since the graph works (when I hardcode the value).

In my views file, I have the following code to get the input from the user and then place it in the required place for the query.

views.py

class ChartData(APIView):
    authentication_classes = []
    permission_classes = []


    def post(self, request, format=None):
        display_id = self.request.POST.get("textfield")

        print(request.data)

        try:
           display_id = int(display_id) 
        except ValueError: 
           display_id = 2

        return display_id

    def get(self, request, format=None):

        display_id = self.request.POST.get("textfield")


        print('value of display_id ')
        print(display_id)

        #insert value from form into parent= below
        all_entries = models.Entries.objects.all().filter(parent=display_id)
        all_measurables = models.Measurables.objects.all().filter(user_id=request.user.id) #change to current user


        all_times = [m.timestamp for m in all_entries]

        all_data = []
        for m in all_entries:
            data = m.data
            json_data = json.loads(data)
            value = json_data['value']
            all_data.append(value)


        data = {
            "labels": all_times,
            "default": all_data,
        }   
        return Response(data)

However, when I run this program, upon entering a number into the textfield and hitting submit the value of display_id seems to be None. Where am I going wrong and how can I achieve what I am trying to do?

FlameDra
  • 1,239
  • 5
  • 20
  • 36
  • The one that calls your get method is the ajax in your html. If you notice, that request does not pass the `textfield` form field. Aside from that, the GET request does not have a POST attribute. You can't pass anything that way because it's a GET request, which means you have to pass it via some other way (e.g., url parameter) or change the ajax method to be POST instead of GET. – munsu Apr 26 '17 at 04:33
  • I suggest doing your tests in shell, it will save you a whole lot of unnecessary headache. You know what is being sent through Ajax, and its values, if you don't know, you can use console to see what is being sent, then you can use that value to test your code in Shell. – almost a beginner Apr 26 '17 at 05:21
  • @RobinAnupol how can I add another AJAX call to get the data from the form? Can you show me some code? I need the GET ajax to pass data from views.py into the html so I can't change it to POST. – FlameDra Apr 26 '17 at 08:04
  • @FlameDra sure you can change it to POST. Both methods should actually return a Response object. Copy paste the inside of your get method to your post method. Then change your html: override your form's submit to be something like this: http://stackoverflow.com/a/6960586/2365267 – munsu Apr 26 '17 at 08:50
  • @RobinAnupol Do I just add that in a – FlameDra Apr 26 '17 at 13:55

0 Answers0