Trying to figure out syntax to evaluate a string from the database using
Django
I have question regarding a method eval, I initially wanted to create a
separate Def to handle user inputs answers from a form.. the problem is
that method wont work because I don't know how to pass the local variable
to another def since the random value will be different in the another
function anyway.
Essentially the ran_puzz pulls a random puzzle from the database which has
a value like "2+2" etc.
rand_puzz = Puzzles.objects.get(id = random_index).puzzle
So I figured since I did not know how to pass rand_puzz to another def, I
decided to keep the variable and logic inside the def called "play" and
return more then one value like" message and ran_puzz"
If you see the line "if eval(rand_puzz)== user_sub_ans;" // This is causes
syntax errors
URLS:
url(r'^play/$', 'mathgame3.views.play'),
VIEWS: def play(request)
if request.user.is_authenticated():
number_of_records = Puzzles.objects.count()
random_index = int(random.random()*number_of_records)+1
rand_puzz = Puzzles.objects.get(id = random_index).puzzle
user_sub_ans = request.GET['answer']
if eval(rand_puzz)== user_sub_ans;
message = 'correct'
else:
message = 'incorrect'
return render(request, 'play.html', {'rand_puzz': rand_puzz,
'message': message})
else:
return render_to_response('home.html')
Html: Just a chunk of some code from the form that the user inputs an
answer to the puzzle.
<form action="/play/" method = "get">
<table style="margin-left:auto; margin-right:auto; width:auto;">
<table style="margin-left:auto; margin-right:auto; width:auto;
border:solid 1px">
<tr><td><label for="username">Question:</label></td>
<td>{{rand_puzz}}</td></tr>
<tr><td><label for="answer">Answer:</label></td>
<td><input type="number" name="answer" value="" id="answer"></td></tr>
<td> The answer is: {{message}}</td></tr>
<tr><td></td><td><input type="submit" value="Submit"/></td></tr>
</table>
</table>
</form>
I would appreciate the help.
No comments:
Post a Comment