59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
import locale
|
|
|
|
from django.contrib.auth.models import User
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
from django.db import transaction
|
|
from django.utils.encoding import force_text
|
|
|
|
from docbow_project.docbow.models import MailingList
|
|
|
|
|
|
def get_object(model, ref):
|
|
'''Try to get a model by id or by name'''
|
|
if ref.isdigit():
|
|
return model.objects.get(id=int(ref))
|
|
else:
|
|
return model.objects.get(name=ref)
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
help = '''Create or update a list'''
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('ml_name', type=str, help='Name of the mailing list')
|
|
parser.add_argument(
|
|
"--add-list", action="append", help='add a list as a sublist', default=[],
|
|
)
|
|
parser.add_argument(
|
|
"--remove-list", action="append", help='remove list as a sublist', default=[],
|
|
)
|
|
parser.add_argument("--add-user", action="append", help='add a user member', default=[])
|
|
parser.add_argument("--remove-user", action="append", help='remove a user member', default=[])
|
|
|
|
@transaction.atomic
|
|
def handle(self, **options):
|
|
locale.setlocale(locale.LC_ALL, '')
|
|
locale_encoding = locale.nl_langinfo(locale.CODESET)
|
|
mailing_list, created = MailingList.objects.get_or_create(
|
|
name=force_text(options['ml_name'], locale_encoding)
|
|
)
|
|
try:
|
|
for l in options['add_list']:
|
|
l = get_object(MailingList, l)
|
|
mailing_list.mailing_list_members.add(l)
|
|
for l in options['remove_list']:
|
|
l = get_object(MailingList, l)
|
|
mailing_list.mailing_list_members.remove(l)
|
|
except MailingList.DoesNotExist:
|
|
raise CommandError('list %r does not exist' % l)
|
|
try:
|
|
for g in options['add_user']:
|
|
g = get_object(User, g)
|
|
mailing_list.members.add(g)
|
|
for g in options['remove_user']:
|
|
g = get_object(User, g)
|
|
mailing_list.members.remove(g)
|
|
except User.DoesNotExist:
|
|
raise CommandError('user %r does not exist' % g)
|