django.conf.settings.ADMINS

Here are the examples of the python api django.conf.settings.ADMINS taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

3 Source : __init__.py
with GNU General Public License v3.0
from Aghoreshwar

def mail_admins(subject, message, fail_silently=False, connection=None,
                html_message=None):
    """Send a message to the admins, as defined by the ADMINS setting."""
    if not settings.ADMINS:
        return
    mail = EmailMultiAlternatives(
        '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message,
        settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
        connection=connection,
    )
    if html_message:
        mail.attach_alternative(html_message, 'text/html')
    mail.send(fail_silently=fail_silently)


def mail_managers(subject, message, fail_silently=False, connection=None,

3 Source : __init__.py
with MIT License
from Air-999

def mail_admins(subject, message, fail_silently=False, connection=None,
                html_message=None):
    """Send a message to the admins, as defined by the ADMINS setting."""
    if not settings.ADMINS:
        return
    if not all(isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.ADMINS):
        raise ValueError('The ADMINS setting must be a list of 2-tuples.')
    mail = EmailMultiAlternatives(
        '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message,
        settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
        connection=connection,
    )
    if html_message:
        mail.attach_alternative(html_message, 'text/html')
    mail.send(fail_silently=fail_silently)


def mail_managers(subject, message, fail_silently=False, connection=None,

3 Source : __init__.py
with MIT License
from chunky2808

def mail_admins(subject, message, fail_silently=False, connection=None,
                html_message=None):
    """Sends a message to the admins, as defined by the ADMINS setting."""
    if not settings.ADMINS:
        return
    mail = EmailMultiAlternatives(
        '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message,
        settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
        connection=connection,
    )
    if html_message:
        mail.attach_alternative(html_message, 'text/html')
    mail.send(fail_silently=fail_silently)


def mail_managers(subject, message, fail_silently=False, connection=None,

3 Source : __init__.py
with Apache License 2.0
from lumanjiao

def mail_admins(subject, message, fail_silently=False, connection=None,
                html_message=None):
    """Sends a message to the admins, as defined by the ADMINS setting."""
    if not settings.ADMINS:
        return
    mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
                message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
                connection=connection)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')
    mail.send(fail_silently=fail_silently)


def mail_managers(subject, message, fail_silently=False, connection=None,

3 Source : emails.py
with MIT License
from marcosgabarda

    def __init__(
        self,
        subject: Optional[str] = None,
        context: Optional[Dict] = None,
        from_email: Optional[str] = None,
    ):
        to: Union[str, List] = [a[1] for a in settings.ADMINS]
        super().__init__(to, subject=subject, context=context, from_email=from_email)


class ManagersTemplateEmailMessage(TemplateEmailMessage):

3 Source : tests.py
with GNU General Public License v2.0
from puncoder

    def test_register_user_and_activate_by_admin(self):
        response = self.assert_user_registration('plan-tester', follow=True)

        self.assertContains(
            response,
            'Your account has been created, but you need an administrator to activate it')

        for (name, email) in settings.ADMINS:
            self.assertContains(response,
                                '  <  a href="mailto:{}">{} < /a>'.format(email, name),
                                html=True)


class TestConfirm(TestCase):

3 Source : send_suspicious_mail.py
with GNU General Public License v2.0
from widelands

    def handle(self, *args, **options):
        spams = SuspiciousInput.objects.all()
        if spams:
            message = 'There were %d hidden posts found:' % len(spams)
    
            for spam in spams:
                app = ContentType.objects.get_for_id(
                    spam.content_type_id)
                message += '\nIn %s/%s: ' % (app.app_label, app.model)
                message += '\n User \'%s\' wrote: %s' % (spam.user, spam.text)
    
            message += '\n\nAdmin page: https://%s/admin/pybb/post/' % Site.objects.get_current().domain
            recipients = [addr[1] for addr in settings.ADMINS]
            send_mail('Hidden posts were found', message, '[email protected]',
                      recipients, fail_silently=False)

0 Source : serializers.py
with Apache License 2.0
from aropan

    def generate_feed(self, data, options=None):
        options = options or {}
        data = self.to_simple(data, options)
        fg = FeedGenerator()
        fg.id(str(hash(json.dumps(data.get('meta', data), sort_keys=True))))
        fg.link(href=reverse_url('clist:main'))
        fg.title('CLIST Feed')
        fg.description('Events of competitive programming')
        fg.icon(reverse_url('favicon'))
        fg.logo(reverse_url('favicon'))
        name, email = settings.ADMINS[0]
        fg.author(name=name, email=email)
        if isinstance(data.get('objects'), Iterable):
            template = get_template('tastypie_swagger/atom_content.html')
            for contest in data['objects']:
                resource = contest['releated_resource']
                fe = fg.add_entry()
                fe.guid(str(contest['id']))
                fe.title(str(contest['event']))
                fe.link(href=contest['href'])
                fe.author(name=resource['name'], uri=resource['url'])
                fe.source(title=resource['name'], url=resource['url'])
                fe.updated(str(arrow.get(contest['updated'])))
                fe.published(str(arrow.get(contest['start_time'])))
                fe.content(template.render({
                    'contest': contest,
                    'resource': resource,
                    'host': settings.HTTPS_HOST_
                }))
        else:
            fg.description(json.dumps(data))
        return fg

    def to_atom(self, *args, **kwargs):

0 Source : event_mailing.py
with Apache License 2.0
from aropan

    def handle(self, *args, **options):
        event = Event.objects.filter(name__iregex=options['event']).order_by('-created').first()
        self.stdout.write(f'event = {event}')
        template = get_template(options['template'])
        status = getattr(TeamStatus, options['status'].upper())

        teams = Team.objects.filter(
            modified__lt=now() - timedelta(minutes=2),
            event=event,
            status=status,
        )

        n_attempet = 3
        failed = 0
        done = 0
        time_wait_on_success = 2
        time_wait_on_failed = 10

        with event.email_backend() as connection:
            logins = [team.login_set.get(stage=status) for team in teams]
            with tqdm.tqdm(zip(teams, logins), total=len(logins)) as pbar:
                for team, login in pbar:
                    context = {'team': team, 'login': login}
                    jobs = []
                    if options['dryrun']:
                        email = settings.ADMINS[0][1]
                        jobs = [{'email': [email], 'coder': Coder.objects.get(username='aropan')}]
                    else:
                        if options['each']:
                            jobs = [{'email': [p.email], 'coder': p.coder} for p in team.ordered_participants]
                        else:
                            jobs = [{'email': [p.email for p in team.ordered_participants]}]

                    for job in jobs:
                        context.update(job)
                        message = template.render(context)
                        subject, message = message.split('\n\n', 1)
                        message = message.replace('\n', '  <  br>\n')
                        msg = EmailMultiAlternatives(
                            subject,
                            message,
                            to=job['email'],
                            connection=connection,
                        )
                        msg.attach_alternative(message, 'text/html')

                        for i in range(n_attempet):
                            try:
                                result = msg.send()
                                if result:
                                    done += 1
                                    time.sleep(time_wait_on_success)
                                    break
                            except Exception as e:
                                print(e)
                            time.sleep(time_wait_on_failed * (i + 1))
                        else:
                            failed += 1
                        pbar.set_postfix(done=done, failed=failed)
                        if options['dryrun']:
                            return

        self.stdout.write(f'Successfully mailing: {done} of {teams.count()} ({failed} fails)')

0 Source : forms.py
with Apache License 2.0
from gethue

  def clean(self):
    if conf.AUTH.EXPIRES_AFTER.get() > -1:
      try:
        user = User.objects.get(username=self.cleaned_data.get('username'))

        expires_delta = datetime.timedelta(seconds=conf.AUTH.EXPIRES_AFTER.get())
        if user.is_active and user.last_login and user.last_login + expires_delta   <   datetime.datetime.now():
          INACTIVE_EXPIRATION_DELTA = datetime.timedelta(days=365)
          if is_admin(user):
            if conf.AUTH.EXPIRE_SUPERUSERS.get():
              user.is_active = False
              user.last_login = datetime.datetime.now() + INACTIVE_EXPIRATION_DELTA
              user.save()
          else:
            user.is_active = False
            user.last_login = datetime.datetime.now() + INACTIVE_EXPIRATION_DELTA
            user.save()

        if not user.is_active:
          if settings.ADMINS:
            raise ValidationError(mark_safe(_("Account deactivated. Please contact an  < a href=\"mailto:%s\">administrator < /a>.") % settings.ADMINS[0][1]))
          else:
            raise ValidationError(self.error_messages['inactive'])
      except User.DoesNotExist:
        # Skip because we couldn't find a user for that username.
        # This means the user managed to get their username wrong.
        pass

    return self.authenticate()


class OrganizationAuthenticationForm(Form):

0 Source : views_test.py
with Apache License 2.0
from gethue

  def test_login_expiration(self):
    response = self.c.post('/hue/accounts/login/', {
        'username': self.test_username,
        'password': "test-hue-foo2",
      }, follow=True)
    assert_equal(200, response.status_code, "Expected ok status.")

    self.reset.append(conf.AUTH.EXPIRES_AFTER.set_for_testing(10000))
    user = User.objects.get(username=self.test_username)
    user.last_login = datetime.datetime.now() + datetime.timedelta(days=-365)
    user.save()

    # Deactivate user
    old_settings = settings.ADMINS
    settings.ADMINS = []
    response = self.c.post('/hue/accounts/login/', {
        'username': self.test_username,
        'password': "test-hue-foo2",
      }, follow=True)
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true("Account deactivated. Please contact an administrator." in response.content, response.content)
    settings.ADMINS = old_settings

    # Activate user
    user = User.objects.get(username=self.test_username)
    user.is_active = True
    user.save()
    response = self.c.post('/hue/accounts/login/', dict(username=self.test_username, password="foo"))
    assert_equal(200, response.status_code, "Expected ok status.")


class TestLdapLogin(PseudoHdfsTestBase):

0 Source : views_test.py
with Apache License 2.0
from gethue

  def test_login_expiration(self):
    """ Expiration test without superusers """
    old_settings = settings.ADMINS
    self.reset.append( conf.AUTH.BACKEND.set_for_testing(["desktop.auth.backend.AllowFirstUserDjangoBackend"]) )
    self.reset.append( conf.AUTH.EXPIRES_AFTER.set_for_testing(0) )
    self.reset.append( conf.AUTH.EXPIRE_SUPERUSERS.set_for_testing(False) )

    client = make_logged_in_client(username=self.test_username, password="test")
    client.get('/accounts/logout')
    user = User.objects.get(username=self.test_username)

    # Login successfully
    try:
      user.is_superuser = True
      user.save()
      response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")

      client.get('/accounts/logout')

      # Login fail
      settings.ADMINS = [(self.test_username, '[email protected]')]
      user.is_superuser = False
      user.save()
      response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")
      assert_true('Account deactivated. Please contact an   <  a href="mailto:[email protected]">administrator < /a>' in response.content, response.content)

      # Failure should report an inactive user without admin link
      settings.ADMINS = []
      response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")
      assert_true("Account deactivated. Please contact an administrator." in response.content, response.content)
    finally:
      settings.ADMINS = old_settings

  def test_login_expiration_with_superusers(self):

0 Source : base.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools

    def failure_recipients(self):
        return tuple(item[1] for item in settings.ADMINS)

    def execute(self, *args, **options):

0 Source : forms.py
with Apache License 2.0
from lumanjiao

  def clean(self):
    if conf.AUTH.EXPIRES_AFTER.get() > -1:
      try:
        user = User.objects.get(username=self.cleaned_data.get('username'))

        expires_delta = datetime.timedelta(seconds=conf.AUTH.EXPIRES_AFTER.get())
        if user.is_active and user.last_login + expires_delta   <   datetime.datetime.now():
          if user.is_superuser:
            if conf.AUTH.EXPIRE_SUPERUSERS.get():
              user.is_active = False
              user.save()
          else:
            user.is_active = False
            user.save()

        if not user.is_active:
          if settings.ADMINS:
            raise ValidationError(mark_safe(_("Account deactivated. Please contact an  < a href=\"mailto:%s\">administrator < /a>.") % settings.ADMINS[0][1]))
          else:
            raise ValidationError(self.error_messages['inactive'])
      except User.DoesNotExist:
        # Skip because we couldn't find a user for that username.
        # This means the user managed to get their username wrong.
        pass

    return self.authenticate()


class LdapAuthenticationForm(AuthenticationForm):

0 Source : views_test.py
with Apache License 2.0
from lumanjiao

  def test_login_expiration(self):
    """ Expiration test without superusers """
    old_settings = settings.ADMINS
    self.reset.append( conf.AUTH.BACKEND.set_for_testing(["desktop.auth.backend.AllowFirstUserDjangoBackend"]) )
    self.reset.append( conf.AUTH.EXPIRES_AFTER.set_for_testing(0) )
    self.reset.append( conf.AUTH.EXPIRE_SUPERUSERS.set_for_testing(False) )

    client = make_logged_in_client(username=self.test_username, password="test")
    client.get('/accounts/logout')
    user = User.objects.get(username=self.test_username)

    # Login successfully
    try:
      user.is_superuser = True
      user.save()
      response = client.post('/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")

      client.get('/accounts/logout')

      # Login fail
      settings.ADMINS = [(self.test_username, '[email protected]')]
      user.is_superuser = False
      user.save()
      response = client.post('/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")
      assert_true('Account deactivated. Please contact an   <  a href="mailto:[email protected]">administrator < /a>' in response.content, response.content)

      # Failure should report an inactive user without admin link
      settings.ADMINS = []
      response = client.post('/accounts/login/', dict(username=self.test_username, password="test"), follow=True)
      assert_equal(200, response.status_code, "Expected ok status.")
      assert_true("Account deactivated. Please contact an administrator." in response.content, response.content)
    finally:
      settings.ADMINS = old_settings

  def test_login_expiration_with_superusers(self):

0 Source : settings_test.py
with BSD 3-Clause "New" or "Revised" License
from mitodl

    def test_admin_settings(self):
        """Verify that we configure email with environment variable"""

        settings_vars = self.patch_settings(
            {**REQUIRED_SETTINGS, "MITXPRO_ADMIN_EMAIL": ""}
        )
        self.assertFalse(settings_vars.get("ADMINS", False))

        test_admin_email = "[email protected]"
        settings_vars = self.patch_settings(
            {**REQUIRED_SETTINGS, "MITXPRO_ADMIN_EMAIL": test_admin_email}
        )
        self.assertEqual((("Admins", test_admin_email),), settings_vars["ADMINS"])

        # Manually set ADMIN to our test setting and verify e-mail
        # goes where we expect
        settings.ADMINS = (("Admins", test_admin_email),)
        mail.mail_admins("Test", "message")
        self.assertIn(test_admin_email, mail.outbox[0].to)

    def test_csrf_trusted_origins(self):

0 Source : checks.py
with MIT License
from PacktPublishing

def settings_check(app_configs, **kwargs):
    from django.conf import settings

    errors = []

    if not settings.ADMINS:
        errors.append(Warning(
            """
The system admins are not set in the project settings
""",
            obj=settings,
            hint="""
            In order to receive notifications when new videos are
            created, define system admins in your settings, like:

            ADMINS = (
                ("Admin", "[email protected]"),
            )
""",
            id="viral_videos.W001"))

    return errors

0 Source : checks.py
with MIT License
from PacktPublishing

def settings_check(app_configs, **kwargs):
    from django.conf import settings

    errors = []

    if not settings.ADMINS:
        errors.append(
            Warning(
                dedent("""
                    The system admins are not set in the project settings
                """),
                obj=settings,
                hint=dedent("""
                    In order to receive notifications when new videos are
                    created, define system admins in your settings, like:
        
                    ADMINS = (
                        ("Admin", "[email protected]"),
                    )
                """),
                id="viral_videos.W001",
            )
        )

    return errors

0 Source : signals.py
with GNU General Public License v2.0
from puncoder

def notify_admins(sender, **kwargs):
    """
        Very simple signal handler which sends emails to site
        admins when a new user has been registered!

        .. warning::

            This handler isn't connected to the ``USER_REGISTERED_SIGNAL`` by default!
    """
    from django.urls import reverse
    from django.conf import settings
    from django.utils.translation import ugettext_lazy as _

    from tcms.core.utils.mailto import mailto
    from tcms.core.utils import request_host_link

    request = kwargs.get('request')
    user = kwargs.get('user')

    admin_emails = []
    for _name, email in settings.ADMINS:
        admin_emails.append(email)

    user_url = request_host_link(request) + reverse('admin:auth_user_change', args=[user.pk])

    mailto(
        template_name='email/user_registered/notify_admins.txt',
        recipients=admin_emails,
        subject=str(_('New user awaiting approval')),
        context={
            'username': user.username,
            'user_url': user_url,
        }
    )


def handle_emails_post_case_save(sender, instance, created=False, **_kwargs):

0 Source : 0002_create_superusers.py
with MIT License
from rtcharity

def admin_emails():
    return (email.lower() for _, email in settings.ADMINS)


def create_superusers(apps, schema_editor):

0 Source : auditpayments.py
with MIT License
from StanfordHCI

def admin_email_address():
    return "%s   <  %s>" % (settings.ADMINS[0][0], settings.ADMINS[0][1])

def get_salt():