Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django views if statement not working with a boolean

My if statment always goes to the Else even if the boolean value changes? Working 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 model.py for email confirmed

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)
like image 911
UK2AU Avatar asked Feb 25 '15 11:02

UK2AU


2 Answers

Your print statement shows True or False because you are returning the string representation of a boolean value in your str override. In other words, you are printing the strings 'True' or 'False'. The actual boolean field confirmed is a field in your model. You should change your if condition to:

if not confirmed.confirmed:
    ...

By the way, it may be a better idea to use get_object_or_404 method instead of get() to return a 404 page instead of a server error when no EmailConfirmed objects could be 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:
        ...
like image 126
Selcuk Avatar answered Sep 28 '22 02:09

Selcuk


I adapted the code from catavaran & 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"))

This is now working with my test cases.

like image 30
UK2AU Avatar answered Sep 28 '22 03:09

UK2AU