Reputation: 19
I am trying to show the multiplication table of a number from a form. Here is my tamplate.
<form method="post" action="/home/result/">
<p>Enter your name</p>
<p><input type="text" name="nombre"></p>
<p>Enter you last name</p>
<p><input type="text" name="apellido"></p>
<p>Enter number for the table of that number</p>
<p><input type="number" name="table1"></p>
<p><input type="submit" name="Submit"></p>
</form>
Now, here is my view
@csrf_exempt
def get_name(request):
numbers = []
if request.method == 'POST':
nombre = request.POST.get('nombre')
apellido = request.POST.get('apellido')
table = request.POST.get('table1')
for i in range(1, 13):
numbers.append(i*table)
context = {
'nombre': nombre,
'apellido': apellido,
'numbers': numbers
}
template = loader.get_template('home/result.html')
return HttpResponse(template.render(context, request))
else:
template = loader.get_template('home/nombre.html')
return HttpResponse(template.render())
Here is my other view, result.html
<p>Hello {{ nombre }} {{ apellido }}</p>
{% for number in numbers %}
{{ number }}<br />
{% endfor %}
So, I enter 6, this is what I see. I tried this on my terminal and I get the right result. What could it be wrong?
6
66
666
6666
66666
666666
6666666
66666666
666666666
6666666666
66666666666
666666666666
Upvotes: 0
Views: 82
Reputation: 771
To expand upon the other answer given, table is a string when you get it from the post body. You must convert it to an integer with the int()
function. In the context of your code:
def get_name(request):
numbers = []
if request.method == 'POST':
nombre = request.POST.get('nombre')
apellido = request.POST.get('apellido')
table = request.POST.get('table1', 0) # this adds a default, in case table1 is empty
table = int(table) # converts the string into an integer
...
then you just continue on how you were from there.
for reference, you should never use @csrf_exempt
in a production application unless you have a really, really good reason for doing so.
Upvotes: 0
Reputation: 655
The issue you're having here is that the '6' you are passing to the view is actually a string. So when you multiply it, you are performing string multiplication which just repeats the string.
To fix this, you must convert the number to an integer by doing int(table)
Upvotes: 3