【问题标题】:Flipping a boolean value with a simple view in Django?在 Django 中使用简单视图翻转布尔值?
【发布时间】:2010-07-30 03:33:20
【问题描述】:

我有一个简单的视图,但不能让它做它应该做的事情,这只是翻转一个布尔值:

def change_status(request):
 request.user.get_profile().active=not request.user.get_profile().active
 return render_to_response('holdstatus.html', {
  'user' : request.user,
 })

除了“not”之外,我试过'-'和'!',但都无济于事。

【问题讨论】:

    标签: django boolean


    【解决方案1】:

    您需要将更改保存到数据库中。

    def change_status(request):
        profile = request.user.get_profile()
        profile.active = not profile.active
        profile.save()
        return render_to_response('holdstatus.html', {
           'user': request.user,
        })
    

    【讨论】:

    • 谢谢!那工作得很好。很高兴我并没有离得太远。
    【解决方案2】:

    迟到但可能会帮助别人。 您可以使用^= True 进行切换。在个人资料中切换active 字段,例如:-

    profile = request.user.get_profile()
    profile.active ^= True
    profile.save()
    

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多