-1

I have an Django app which check if the the database holds numbers which matches the numbers entered by the user in the form. I've managed to get it to redirect to the 'You win' page if they do match but when they don't match it just gives an error saying 'matching query does not exist.' Here's the if/else statement I'm using in the view.py file:

if Numbers.objects.get(numbers_win = user_number):
     return HttpResponseRedirect('win')
else:
     return HttpResponseRedirect('lose.html')
RickyA
  • 15,465
  • 5
  • 71
  • 95
CNB
  • 27
  • 7
  • 1
    What does `Numbers.object.get..` returns ? Are you sure it returns a boolean ? – Mel Jan 08 '16 at 12:47
  • 2
    Maybe this will help: http://stackoverflow.com/questions/3090302/in-django-how-do-i-objects-get-but-return-none-when-nothing-is-found So you would have to surround it with try except instead of if. – allu Jan 08 '16 at 12:47

1 Answers1

6

That's because .get throws an exception when there are no matches — it doesn't return something falsey.

You have two options:

First, you can use filter and existsinstead of get, which will return True if something is found, and False otherwise.

If you're not otherwise using the result, this is probably the best solution:

if Numbers.objects.filter(numbers_win = user_number).exists():
     return HttpResponseRedirect('win')
else:
     return HttpResponseRedirect('lose.html')

(As noted in the comments, using exists is faster if you're just checking for existence)

Second, you could catch the exception instead of using if / else:

try:
    Numbers.objects.get(numbers_win = user_number)
except Numbers. DoesNotExist:
    return HttpResponseRedirect('lose.html')
else:  
    return HttpResponseRedirect('win')

As you can see, though, this makes for somewhat awkward code, and it also performs worse than using .exists, so you probably shouldn't do this.

jpic
  • 32,891
  • 5
  • 112
  • 113
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116