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 the following form in my project.
Display.html
<div class="row">
<form method="POST">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Submit</button>
</form>
</div>
In my views file, I have the following code to get the data from this form:
views.py
class ChartData(APIView):
authentication_classes = []
permission_classes = []
display_id = 0
def post(self, request, format=None):
display_id = self.request.POST.get("textfield")
try:
display_id = int(display_id)
except ValueError:
display_id = 2
def get(self, request, format=None):
display_id = self.request.GET.get("textfield")
all_entries = models.Entries.objects.all().filter(parent=display_id) #change to input from text box via display_id
all_id = models.Entries.objects.all().values_list('id', flat=True)
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)
My urls are set up as follows.
urls.py
from .views import get_data, ChartData
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'),
]
When I go into the form in the page and type in a number and hit submit, in my console I get the following error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
What am I doing wrong?
Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post()
If you doing a POST request.You have to do
def post(self, request, format=None):
#rest of code
display_id = request.POST.get("textfield")
error with this line. you are missing self. here it is returning NoneType. And change your method to post
def post(self, request, format=None):
display_id = self.request.POST.get("textfield")
try:
display_id = int(display_id)
except ValueError:
display_id = "here you give default value"
you got this error because you are trying to pass non-integer value as a string