我希望能够通过我的视图更改用户的“sendmail”布尔值。但是,为具有值True的用户添加一次对象后,我无法再更改它,因为我在/ accounts / send_me_email / column user_id处获得“IntegrityError”并不是唯一的。我做错了什么?
models.py class SendMeMail(models.Model): user = models.ForeignKey(User, unique=True) sendmail = models.BooleanField()
views.py from userprofile.models import SendMeMail def send_me_email(request): """ Define if a user want email notifications or not """ # Check for current sendmail value and act accordingly sendme = SendMeMail(user=request.user) if sendme.sendmail == False: sendme.sendmail = True sendme.save() if sendme.sendmail == True: sendme.sendmail = False sendme.save() else: sendme.sendmail = True sendme.save()
答案 0 :(得分:0)
这一行:
sendme = SendMeMail(user=request.user)
没有按照你声称的那样做。它不会从数据库中加载当前用户的SendMeMail对象 - 它会为该用户创建一个 new 对象。由于您(正确地)将用户字段声明为唯一,因此在保存时失败。
相反,你的意思是:
sendme = SendMeMail.objects.get(user=request.user)
答案 1 :(得分:0)
并且可能会改变
if sendme.sendmail == False:
sendme.sendmail = True
sendme.save()
if sendme.sendmail == True:
sendme.sendmail = False
sendme.save()
else:
sendme.sendmail = True
sendme.save()
到
sendme.sendmail = !sendme.sendmail
sendme.save()
它更短我认为)