开发者

Change boolean value for user object

开发者 https://www.devze.com 2023-02-28 20:37 出处:网络
I want to be 开发者_运维技巧able to change my \"sendmail\" boolean value for a user via my view. But after adding the object once for a user with the value True I can\'t change it anymore because I ge

I want to be 开发者_运维技巧able to change my "sendmail" boolean value for a user via my view. But after adding the object once for a user with the value True I can't change it anymore because I get an "IntegrityError at /accounts/send_me_email/ column user_id is not unique". What am I doing wrong?

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()


This line:

sendme = SendMeMail(user=request.user)

doesn't do what you claim it does. It doesn't load the SendMeMail object with the current user from the database - it creates a new object for that user. Since you've (correctly) declared the user field as unique, this fails on save.

Instead, you mean this:

sendme = SendMeMail.objects.get(user=request.user)


and maybe change

if sendme.sendmail == False:
    sendme.sendmail = True
    sendme.save()
if sendme.sendmail == True:
    sendme.sendmail = False
    sendme.save()
else:
    sendme.sendmail = True
    sendme.save()

to

sendme.sendmail = !sendme.sendmail
sendme.save()

it's shorter i think)

0

精彩评论

暂无评论...
验证码 换一张
取 消