exec() function in python not executing in django

Viewed 114

Hope you all are fine. I want to use the exec() function in django to execute my strings picked from the database. The code I wrote is working in just python script but not working in Django views. Below is my code in python script which I'm running in notebook.

ticker = 'AAPL'
title = 'f"hey {ticker} is a really doing good."'
exec('title = ' + title)
print(title)

But same code in Django views is not executing. Below is the code in views.py.

ticker = 'AAPL'
title = queryset.title #The title here is The {ticker} is not doing good.
exec('title = ' + title)

It is not giving the write anwser, just returning the first title as shown below.

The {ticker} is not doing good. Thats is the {ticker} body.

If anyone have any solution, kindly help me to figure it out.

2 Answers

Use str.format(…) [Python-doc] to format strings:

ticker = 'AAPL'
title = queryset.title.format(ticker=ticker)

do not use exec or eval: it can result in unwanted side-effects and is thus not secure.

I found the answer. If you want to execute one variable, then use the upper code which is:

ticker = 'AAPL'
title = queryset.title.format(ticker=ticker)

If you want to execute whole dictionary with alot of values. Then ** is a good option. For example

dictionary = {'ticker': 'Example', 'website': 'example.com'}
queryset.title.format(**dictionary)
Related