简体   繁体   中英

Using Django Framework to compare User form answer as an input and comparing it with a evaluation for a math expression using eval

I am having problem coding and figuring out how to compare a value as an answer from the user input of a form and using that input to compare it with eval(puzzle) which puzzle is a simple expression like 2+2

Here is some code.

Url: is fine.

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
    solution = eval(rand_puzz)
    if solution = request.GET['a']:
       message = "correct"
       return render(request, 'play.html', {'rand_puzz': rand_puzz, 'message':message})
    else: 
       message = "incorrect"
    return render(request, 'play.html', {'rand_puzz': rand_puzz, message':message})
else:
    return render_to_response('home.html')

HTML:

    <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>
    <td><input type="number" name="a" value="a" id="a"></td></tr>
    <td>{{solution}}</td></tr> 
     <td> Your answer is:{{message}}</td></tr>
<tr><td></td><td><input type="submit" value="submit"/></td></tr>
</table>
        </table>
    </form>
  </div>  

i don't know if it gonna solve your problem but replace

from django.shortcuts import get_object_or_404

rand_puzz = Puzzles.objects.get(id = random_index).puzzle
by
rand_puzz = get_object_or_404(Puzzles,id = random_index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM