Django views if statement does not work with boolean

Mine if statment always goes in Else, even if boolean value changes? Work in Django 1.6.5

views.py

def awaiting_email_confirmation(request): confirmed = EmailConfirmed.objects.get(user=request.user) print confirmed if confirmed is False: print "if" template = 'accounts/email_confirmation.html' context = {} return render(request, template, context) else: print "else" return HttpResponseRedirect(reverse("dashboard")) 

My console will print

 True else False else 

This is my .py confirmed email model.

 class EmailConfirmed(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) activation_key = models.CharField(max_length=200) confirmed = models.BooleanField(default=False) def __unicode__(self): return str(self.confirmed) 
+6
source share
2 answers

Your print statement shows True or False , because you are returning a string representation of the boolean in the str override. In other words, you print the lines "True" or "False". The actual logical field confirmed is the field in your model. You must change your condition:

 if not confirmed.confirmed: ... 

By the way, it is better to use the get_object_or_404 method instead of get() to return a 404 page instead of a server error if EmailConfirmed objects were not found:

 from django.shortcuts import get_object_or_404 ... def awaiting_email_confirmation(request): confirmed = get_object_or_404(EmailConfirmed, user=request.user) if not confirmed.confirmed: ... 
+2
source

I adapted the code from catavaran and Selcuk.

view.py:

 from django.shortcuts import get_object_or_404 def awaiting_email_confirmation(request): confirmed = get_object_or_404(EmailConfirmed, user=request.user) if not confirmed.confirmed: template = 'accounts/email_confirmation.html' context = {} return render(request, template, context) else: return HttpResponseRedirect(reverse("dashboard")) 

Now we are working with our test cases.

+1
source

Source: https://habr.com/ru/post/982983/


All Articles