即使布尔值发生变化,我的if语句总是会转到Else? 在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"))
我的控制台将打印
True
else
False
else
这是我确认电子邮件的model.py
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)
答案 0 :(得分:2)
您的print
语句显示True
或False
,因为您在str
覆盖中返回布尔值的字符串表示形式。换句话说,您正在打印字符串'True'或'False'。实际的布尔字段confirmed
是模型中的字段。您应该将if条件更改为:
if not confirmed.confirmed:
...
顺便说一下,当找不到get_object_or_404
个对象时,最好使用get()
方法而不是EmailConfirmed
来返回404页面而不是服务器错误:
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:
...
答案 1 :(得分:1)
我改编了catavaran&的代码。塞尔丘克。
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"))
现在正在使用我的测试用例。