how to fetch data into a template (table)

70 views
Skip to first unread message

Faith Mwai

unread,
Jun 20, 2020, 11:41:57 AM6/20/20
to Django users
Am having a challenge of displaying data into my template table, the function is;

def customers(request):
if request.method == 'POST':
accountno = request.POST['accountno']
id= request.POST['id']
Mobilenumber = request.POST['Mobilenumber']
cursor = con.cursor()
querystring = ("Select Messages, amount, date from Accounts where accountno = 'accountno' or Mobilenumber = 'Mobilenumber' ")
    cursor.execute(querystring)
    rows = cursor.fetchall()
context = {'querystring': querystring}
con.close()

if cursor.rowcount == 0:
return render(request,'kplcapp/customers.html', context)
else:
rows = cursor.fetchall()
return render('kplcapp/customers.html', context)
return render(request, 'kplcapp/customers.html', context)

if 'print' in request.form:
df = pd.DataFrame(result)
df.to_excel(
r"C:\Users\Public\Documents\data3.xlsx")
else:
return render(request, 'kplcapp/customers.html', context)

Jatin Agrawal

unread,
Jun 22, 2020, 12:13:55 PM6/22/20
to Django users
Where do you want to display the data? in HTML template?

Faith Mwai

unread,
Jun 22, 2020, 12:24:59 PM6/22/20
to Django users
Yes in an HTML template

Kasper Laudrup

unread,
Jun 22, 2020, 2:59:14 PM6/22/20
to django...@googlegroups.com
Hi Faith,

On 20/06/2020 12.27, Faith Mwai wrote:
> Am having a challenge of displaying data into my template table, the
> function is;
>
> def customers(request):
> if request.method =='POST':
> accountno= request.POST['accountno']
> id= request.POST['id']
> Mobilenumber = request.POST['Mobilenumber']
> cursor = con.cursor()
> querystring = ("Select Messages, amount, date from Accounts where accountno =
> 'accountno' or Mobilenumber = 'Mobilenumber' ")
>
> cursor.execute(querystring)
>

Isn't this a textbook example of an SQL injection?

I seriously don't know if there's anything to prevent that in this code,
but someone else might know.

I'm mainly wondering why you're using raw SQL in the first place?

Kind regards,

Kasper Laudrup

Larry Martell

unread,
Jun 22, 2020, 3:03:22 PM6/22/20
to django...@googlegroups.com
Why are you using raw SQL for such a simple query. In any case you
need to replace the strings with the variables.

querystring = ("Select Messages, amount, date from Accounts where
accountno = '%s' or Mobilenumber = '%s' " % (accountno, Mobilenumber))

Faith Mwai

unread,
Jun 23, 2020, 10:38:19 AM6/23/20
to Django users
Am querying from a table already in production and need data to be real time hence the reason of using the raw sql.
Let me modify and see whether it works
Reply all
Reply to author
Forward
0 new messages