django views if语句不使用布尔值

gt0wga4j  于 2023-05-19  发布在  Go
关注(0)|答案(2)|浏览(182)

我的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)
p3rjfoxz

p3rjfoxz1#

您的print语句显示TrueFalse,因为您在str覆盖中返回布尔值的字符串表示。换句话说,您正在打印字符串“True”或“False”。实际的布尔字段confirmed是模型中的一个字段。您应该将if条件更改为:

if not confirmed.confirmed:
    ...

顺便说一下,当没有找到EmailConfirmed对象时,使用get_object_or_404方法而不是get()返回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:
        ...
7ajki6be

7ajki6be2#

我改编了《双体船与赛尔库克》的代码。
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"))

现在我的测试用例也是如此。

相关问题