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)
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:
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With