[Answered ]-Simple Python script for mass email optout

2👍

You can catch the exception and skip the record using continue. Either by using the exception on the model object itself, User.DoesNotExist:

for email in optouts:
    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        print email, "skipped."
        continue
    profile = user
    profile.allow_mass_mails = False
    profile.save()
    print email, "opted out."

Or by explicitly importing the base exception, django.core.exceptions.ObjectDoesNotExist:

from django.core.exceptions import ObjectDoesNotExist

for email in optouts:
    try:
        user = User.objects.get(email=email)
    except ObjectDoesNotExist:
        print email, "skipped."
        continue
    profile = user
    profile.allow_mass_mails = False
    profile.save()
    print email, "opted out."

Leave a comment