コード例 #1
0
ファイル: openaction.py プロジェクト: openpolis/open-action
    def deliver(self, recipient, sender, notice_type, extra_context):
        """ Deliver a notice to a User 

        DefaultBackend.deliver will send to the receiver (a User) a 
        notification of an action triggered by some other User on an 
        Action or on some article related to it
        """

        # Inspired from django-notification-brosner.backends.EmailBackend
        # 1. Get formatted messages
        context = Context({"recipient": recipient, "sender": sender, "notice": ugettext(notice_type.display)})
        context.update(extra_context)

        messages = self.get_formatted_messages(("short.txt", "full.txt"), notice_type.label, context)

        # 2. Render them with on-site site-wide notification templates
        subject = render_to_string(
            "notification/on_site_notice_subject.txt", {"message": messages["short.txt"]}, context
        )

        text = render_to_string("notification/on_site_notice_text.txt", {"message": messages["full.txt"]}, context)

        notice_text = u"%s%s" % (subject, text)

        # 3. Deliver notice = save new notice for User 'recipient'
        from notification.models import Notice

        Notice.objects.create(recipient=recipient, message=notice_text, notice_type=notice_type, on_site=True)
コード例 #2
0
ファイル: tests.py プロジェクト: DOOMer/screengrab.doomer.org
 def test_has_valid_message_template(self):
     template_exists = 1
     try:
         loader.render_to_string(forms.ContactModelForm.message_template_name)
     except TemplateDoesNotExist:
         template_exists = 0
     self.assertTrue(template_exists, "Email message template does not exist")
コード例 #3
0
ファイル: utils.py プロジェクト: Codeprh/django-users2
def send_activation_email(
        user=None, request=None, from_email=None,
        subject_template='users/activation_email_subject.html',
        email_template='users/activation_email.html', html_email_template=None):

    if not user.is_active and settings.USERS_VERIFY_EMAIL:
        token_generator = EmailActivationTokenGenerator()

        current_site = get_current_site(request)

        context = {
            'email': user.email,
            'site': current_site,
            'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS,
            'user': user,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user=user),
            'protocol': 'https' if request.is_secure() else 'http',
        }

        subject = render_to_string(subject_template, context)
        # email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = render_to_string(email_template, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [user.email])
        if html_email_template is not None:
            html_email = render_to_string(html_email_template, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
コード例 #4
0
def send_mail (subject, to, template, context={}, from_address=settings.DEFAULT_FROM):
  context = email_context(context)
  text = render_to_string(template + '.txt', context)
  html = render_to_string(template + '.html', context)
  
  if type(to) not in (types.TupleType, types.ListType):
    to = [to]
    
  data = {
    'from': from_address,
    'subject': subject.format(**context),
    'to': ','.join(to),
    'text': text,
    'html': html,
  }
  
  if settings.DEV:
    data['to'] = settings.DEV_EMAIL
    data['subject'] = '[Dev] ' + data['subject']
    
  result = requests.post(
    'https://api.mailgun.net/v2/neutrondrive.com/messages',
    data=data,
    auth=('api', settings.MAILGUN),
    timeout=20
  )
  
  if result.status_code == 200:
    return result.text
    
  logging.error(result.text)
  raise MailError('Mail API Error: {}'.format(result.status_code))
  
コード例 #5
0
ファイル: tests.py プロジェクト: DOOMer/screengrab.doomer.org
 def test_has_valid_subject_template(self):
     template_exists = 1
     try:
         loader.render_to_string(forms.ContactForm.subject_template_name)
     except TemplateDoesNotExist:
         template_exists = 0
     self.assertTrue(template_exists, "Subject template does not exist")
コード例 #6
0
    def send(self):
        """
        Sends a reminder email to the user.
        """
        if not self.sent:
            challenge = challenge_mgr.get_challenge()
            subject = "[%s] Reminder for %s" % (challenge.name, self.action.title)
            message = render_to_string(
                "email/activity_reminder.txt",
                {
                    "action": self.action,
                    "user": self.user,
                    "COMPETITION_NAME": challenge.name,
                    "domain": challenge.domain,
                },
            )
            html_message = render_to_string(
                "email/activity_reminder.html",
                {
                    "action": self.action,
                    "user": self.user,
                    "COMPETITION_NAME": challenge.name,
                    "domain": challenge.domain,
                },
            )

            UserNotification.create_email_notification(self.email_address, subject, message, html_message)
            self.sent = True
            self.save()
 def init_password_email(self, user):
     site = Site.objects.get_current()
     ctx_dict = {'site': site, 'organization': settings.TELEMETA_ORGANIZATION, 'usr': user}
     subject = render_to_string(self.subject_template, ctx_dict)
     subject = ''.join(subject.splitlines())
     message = render_to_string(self.message_template, ctx_dict)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
コード例 #8
0
ファイル: models.py プロジェクト: 343max/NewsBlur
 def send_launch_social_email(self, force=False):
     if not self.user.email or not self.send_emails:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email))
         return
     
     sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                            email_type='launch_social')
     
     if not created and not force:
         logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, sent already: %s" % self.user.email)
         return
     
     delta      = datetime.datetime.now() - self.last_seen_on
     months_ago = delta.days / 30
     user    = self.user
     data    = dict(user=user, months_ago=months_ago)
     text    = render_to_string('mail/email_launch_social.txt', data)
     html    = render_to_string('mail/email_launch_social.xhtml', data)
     subject = "NewsBlur is now a social news reader"
     msg     = EmailMultiAlternatives(subject, text, 
                                      from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                      to=['%s <%s>' % (user, user.email)])
     msg.attach_alternative(html, "text/html")
     msg.send(fail_silently=True)
     
     logging.user(self.user, "~BB~FM~SBSending launch social email for user: %s months, %s" % (months_ago, self.user.email))
コード例 #9
0
ファイル: models.py プロジェクト: 343max/NewsBlur
    def send_premium_expire_email(self, force=False):
        if not self.user.email:
            logging.user(self.user, "~FM~SB~FRNot~FM sending premium expire for user: %s" % (self.user))
            return

        emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk,
                                                email_type='premium_expire')
        day_ago = datetime.datetime.now() - datetime.timedelta(days=360)
        for email in emails_sent:
            if email.date_sent > day_ago:
                logging.user(self.user, "~FM~SBNot sending premium expire email, already sent before.")
                return
        
        delta      = datetime.datetime.now() - self.last_seen_on
        months_ago = delta.days / 30
        user    = self.user
        data    = dict(user=user, months_ago=months_ago)
        text    = render_to_string('mail/email_premium_expire.txt', data)
        html    = render_to_string('mail/email_premium_expire.xhtml', data)
        subject = "Your premium account on NewsBlur has expired"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        MSentEmail.record(receiver_user_id=self.user.pk, email_type='premium_expire')
        logging.user(self.user, "~BB~FM~SBSending premium expire email for user: %s months, %s" % (months_ago, self.user.email))
コード例 #10
0
ファイル: models.py プロジェクト: 343max/NewsBlur
    def send_first_share_to_blurblog_email(self, force=False):
        from apps.social.models import MSocialProfile, MSharedStory
        
        if not self.user.email:
            return

        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='first_share')
        
        if not created and not force:
            return
        
        social_profile = MSocialProfile.objects.get(user_id=self.user.pk)
        params = {
            'shared_stories': MSharedStory.objects.filter(user_id=self.user.pk).count(),
            'blurblog_url': social_profile.blurblog_url,
            'blurblog_rss': social_profile.blurblog_rss
        }
        user    = self.user
        text    = render_to_string('mail/email_first_share_to_blurblog.txt', params)
        html    = render_to_string('mail/email_first_share_to_blurblog.xhtml', params)
        subject = "Your shared stories on NewsBlur are available on your Blurblog"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending first share to blurblog email to: %s" % self.user.email)
コード例 #11
0
ファイル: models.py プロジェクト: 343max/NewsBlur
    def send_new_premium_email(self, force=False):
        subs = UserSubscription.objects.filter(user=self.user)
        message = """Woohoo!
        
User: %(user)s
Feeds: %(feeds)s

Sincerely,
NewsBlur""" % {'user': self.user.username, 'feeds': subs.count()}
        mail_admins('New premium account', message, fail_silently=True)
        
        if not self.user.email or not self.send_emails:
            return
        
        sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                                               email_type='new_premium')
        
        if not created and not force:
            return
        
        user    = self.user
        text    = render_to_string('mail/email_new_premium.txt', locals())
        html    = render_to_string('mail/email_new_premium.xhtml', locals())
        subject = "Thanks for going premium on NewsBlur!"
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending email for new premium: %s" % self.user.email)
コード例 #12
0
ファイル: message_helper.py プロジェクト: cchoirat/gentb-site
def send_dataset_run_message_to_tb_admins(dataset_script_run):

    assert isinstance(dataset_script_run, DatasetScriptRun), "dataset_script_run must be a DatasetScriptRun instance"

    if dataset_script_run.result_success:
        subject = "genTB: New file processed (Success)"
    else:
        subject = "genTB: New file processed (Fail)"

    user_email = dataset_script_run.dataset.user.user.email

    d = dict(dataset=dataset_script_run.dataset,
             tb_user=dataset_script_run.dataset.user,
             script_run=dataset_script_run,
             subject=subject,
             SITE_URL=get_site_url())

    if dataset_script_run.result_success:
        text_message = render_to_string('predict/email/pipeline_success_run.txt', d)
        html_message = render_to_string('predict/email/pipeline_success_run.html', d)
    else:
        text_message = render_to_string('predict/email/pipeline_fail_run.txt', d)
        html_message = render_to_string('predict/email/pipeline_fail_run.html', d)

    send_mail_to_user_and_admins(subject, user_email, text_message, html_message)
コード例 #13
0
ファイル: models.py プロジェクト: 343max/NewsBlur
    def send_opml_export_email(self):
        if not self.user.email:
            return
        
        MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk,
                                         email_type='opml_export')
        
        exporter = OPMLExporter(self.user)
        opml     = exporter.process()

        params = {
            'feed_count': UserSubscription.objects.filter(user=self.user).count(),
        }
        user    = self.user
        text    = render_to_string('mail/email_opml_export.txt', params)
        html    = render_to_string('mail/email_opml_export.xhtml', params)
        subject = "Backup OPML file of your NewsBlur sites"
        filename= 'NewsBlur Subscriptions - %s.xml' % datetime.datetime.now().strftime('%Y-%m-%d')
        msg     = EmailMultiAlternatives(subject, text, 
                                         from_email='NewsBlur <%s>' % settings.HELLO_EMAIL,
                                         to=['%s <%s>' % (user, user.email)])
        msg.attach_alternative(html, "text/html")
        msg.attach(filename, opml, 'text/xml')
        msg.send(fail_silently=True)
        
        logging.user(self.user, "~BB~FM~SBSending OPML backup email to: %s" % self.user.email)
コード例 #14
0
ファイル: utils.py プロジェクト: zenith0/django-muecke
def send_customer_added(user):
    """Sends a mail to a newly registered user.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()
    subject = _(u"Welcome to %s" % shop.name)

    from_email = shop.from_email
    to = [user.username]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/new_user_mail.txt", {
        "user": user, "shop": shop})

    # subject
    subject = render_to_string("muecke/mail/new_user_mail_subject.txt", {
        "user": user, "shop": shop})

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/new_user_mail.html", {
        "user": user, "shop": shop,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
コード例 #15
0
ファイル: email.py プロジェクト: jresins/django-notification
    def deliver(self, recipient, notice_type, extra_context):
        # TODO: require this to be passed in extra_context

        context = self.default_context()
        context.update({
            "recipient": recipient,
            # "sender": sender,
            "notice": ugettext(notice_type.display),
        })
        context.update(extra_context)

        messages = self.get_formatted_messages((
            "short.txt",
            "full.txt"
        ), notice_type.label, context)

        subject = "".join(render_to_string("notification/email_subject.txt", {
            "message": messages["short.txt"],
        }, context).splitlines())

        body = render_to_string("notification/email_body.txt", {
            "message": messages["full.txt"],
        }, context)

        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient.email])
コード例 #16
0
ファイル: utils.py プロジェクト: zenith0/django-muecke
def send_review_added(review):
    """Sends a mail to shop admins that a new review has been added
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    subject = _(u"New review has been added")
    from_email = shop.from_email
    to = shop.get_notification_emails()

    ctype = ContentType.objects.get_for_id(review.content_type_id)
    product = ctype.get_object_for_this_type(pk=review.content_id)

    # text
    text = render_to_string("muecke/mail/review_added_mail.txt", {
        "review": review,
        "product": product,
    })

    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to)

    # html
    html = render_to_string("muecke/mail/review_added_mail.html", {
        "site": "http://%s" % Site.objects.get(id=settings.SITE_ID),
        "review": review,
        "product": product,
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
コード例 #17
0
ファイル: utils.py プロジェクト: zenith0/django-muecke
def send_order_received_mail(order):
    """Sends an order received mail to the shop customer.

    Customer information is taken from the provided order.
    """
    import muecke.core.utils
    shop = muecke.core.utils.get_default_shop()

    try:
        subject = render_to_string("muecke/mail/order_received_subject.txt", {"order": order})
    except TemplateDoesNotExist:
        subject = _(u"Your order has been received")

    from_email = shop.from_email
    to = [order.customer_email]
    bcc = shop.get_notification_emails()

    # text
    text = render_to_string("muecke/mail/order_received_mail.txt", {"order": order})
    mail = EmailMultiAlternatives(
        subject=subject, body=text, from_email=from_email, to=to, bcc=bcc)

    # html
    html = render_to_string("muecke/mail/order_received_mail.html", {
        "order": order
    })

    mail.attach_alternative(html, "text/html")
    mail.send(fail_silently=True)
コード例 #18
0
ファイル: views.py プロジェクト: wpjesus/codematch
def get_posted_emails(ipr):
    """Return a list of messages suitable to initialize a NotifyFormset for
    the notify view when a new disclosure is posted"""
    messages = []

    addrs = gather_address_lists('ipr_posting_confirmation',ipr=ipr).as_strings(compact=False)
    context = dict(
        to_email=addrs.to,
        to_name=ipr.submitter_name,
        cc_email=addrs.cc,
        ipr=ipr)
    text = render_to_string('ipr/posted_submitter_email.txt',context)
    messages.append(text)
    
    # add email to related document authors / parties
    if ipr.iprdocrel_set.all():
        messages.extend(get_document_emails(ipr))
    
    # if Generic disclosure add message for General Area AD
    if isinstance(ipr, (GenericIprDisclosure,NonDocSpecificIprDisclosure)):
        role = Role.objects.filter(group__acronym='gen',name='ad').first()
        context = dict(
            to_email=role.email.address,
            to_name=role.person.name,
            ipr=ipr)
        text = render_to_string('ipr/posted_generic_email.txt',context)
        messages.append(text)
        
    return messages
コード例 #19
0
ファイル: email.py プロジェクト: aaronmartin0303/reviewboard
def mail_new_user(user):
    """Sends an e-mail to administrators for newly registered users."""
    current_site = Site.objects.get_current()
    siteconfig = current_site.config.get_current()
    domain_method = siteconfig.get("site_domain_method")
    subject = "New Review Board user registration for %s" % user.username
    from_email = get_email_address_for_user(user)

    context = {
        'domain': current_site.domain,
        'domain_method': domain_method,
        'user': user,
        'user_url': reverse('admin:auth_user_change', args=(user.id,))
    }

    text_message = render_to_string('notifications/new_user_email.txt',
                                    context)
    html_message = render_to_string('notifications/new_user_email.html',
                                    context)

    message = SpiffyEmailMessage(subject.strip(), text_message, html_message,
                                 settings.SERVER_EMAIL, settings.SERVER_EMAIL,
                                 [build_email_address(*a)
                                  for a in settings.ADMINS], None, None)

    try:
        message.send()
    except Exception as e:
        logging.error("Error sending e-mail notification with subject '%s' on "
                      "behalf of '%s' to admin: %s",
                      subject.strip(), from_email, e, exc_info=1)
コード例 #20
0
ファイル: objects_tags.py プロジェクト: wolfmc3/itmemory
def toactivatetask(context, hwobject):
    tasktoactivate = dict()
    for settingitem in hwobject.settings.all():
        tsktype, tskgroup = settingitem.activatetask
        if tsktype:
            tasktoactivate[tsktype.id] = tsktype
        if tskgroup:
            tasktoactivate[tskgroup.id] = tskgroup
    for settingitem in hwobject.softwarepasswords.all():
        tsktype, tskgroup = settingitem.activatetask
        if tsktype:
            tasktoactivate[tsktype.id] = tsktype
        if tskgroup:
            tasktoactivate[tskgroup.id] = tskgroup
    html = ""
    for stask in tasktoactivate.itervalues():
        if stask.tasks.filter(hardwareobject=hwobject).count() == 0:
            html += "<p><a class='btn btn-xs btn-success' href='act_task/{0}'>{2} Attiva {1}</a></p>".format(
                stask.id,
                unicode(stask),
                render_to_string("icon.html", {'iconname': "plus-sign"})
            )
    if not html:
        html = "<p>" + render_to_string("icon.html", {'iconname': "info-sign"}) + "Nessun controllo da attivare</p>"
    return html
コード例 #21
0
ファイル: emails.py プロジェクト: Avatazjoe/apr
def send_cancel_email(appointment):
    current_site = Site.objects.get_current()
    current_site_domain = "http://" + current_site.domain

    c = Context(
        {
            "appointment": appointment,
            "customer": appointment.customer,
            "client": appointment.client,
            "event": appointment.event,
            "current_site_domain": current_site_domain,
        }
    )

    customer_email = "{name} <{email}>".format(name=appointment.customer.name, email=appointment.customer.email)

    email_subject = render_to_string("appointments/email/cancel_notification_subject.txt", c).replace("\n", "")
    email_txt_body = render_to_string("appointments/email/cancel_notification_body.txt", c)
    email_html_body = render_to_string("appointments/email/cancel_notification_body.html", c)

    email_headers = {"X-Mailgun-Campaign-Id": "fg0ec"}

    email = EmailMultiAlternatives(
        email_subject,  # subject
        email_txt_body,  # body
        settings.REMINDER_FROM_EMAIL,  # from
        [customer_email],  # to
        # ['*****@*****.**'],  # bcc
        reply_to=[settings.REMINDER_FROM_EMAIL],
        headers=email_headers,
    )
    email.attach_alternative(email_html_body, "text/html")

    return email.send(fail_silently=False)
コード例 #22
0
ファイル: views.py プロジェクト: etcaterva/EchaloASuerte
    def save(self, subject_template_name, email_template_name,
             token_generator=default_token_generator,
             html_email_template_name=None, **_):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        email = self.cleaned_data["email"]
        user = MONGO.retrieve_user(email)
        c = {
            'email': user.email,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'user': user,
            'token': token_generator.make_token(user),
        }
        subject = loader.render_to_string(subject_template_name, c)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        email = loader.render_to_string(email_template_name, c)

        if html_email_template_name:
            html_email = loader.render_to_string(html_email_template_name, c)
        else:
            html_email = None
        send_mail(subject, email, "*****@*****.**", [user.email], html_message=html_email)
コード例 #23
0
    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject,
                                         bodies['txt'],
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject,
                               bodies['html'],
                               settings.DEFAULT_FROM_EMAIL,
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg
コード例 #24
0
ファイル: views.py プロジェクト: daltemen/undley
def enviar_correo(request):			
	if request.method == 'POST':
		try:			
			data = request.body
			correo = json.loads(data)					
			subject = "Cupon Promocional"  
			from_email = 'Nico de Ebrios <*****@*****.**>'	  
			cliente = correo["id"]
			to = correo["correo"]
			cupon = Cupon.objects.get(pk=1)
			clientedata = get_object_or_404(CustomUser, pk=cliente)			
			contexto = {
				'nombre':clientedata.nombre,
				'apellido':clientedata.apellido,
				'cupon': cupon.serie,
				'descuento':cupon.descuento,
			}
			html_content = render_to_string('email/email.html',Context(contexto))
			txt_content = render_to_string('email/email.html',Context(contexto))						
			send_mail(subject,txt_content,from_email,[to],fail_silently = True, html_message=html_content)			
		except:
			return HttpResponseBadRequest('BAD REQUEST')
		return HttpResponse('YEAH BITCH')
	else:
		return HttpResponseBadRequest('BAD REQUEST')
コード例 #25
0
ファイル: forms.py プロジェクト: littleweaver/django-argus
    def save(self, *args, **kwargs):
        instance = super(GroupForm, self).save(*args, **kwargs)
        if 'email' in self.changed_data:
            # Send confirmation link.
            context = {
                'group': instance,
                'email': instance.email,
                'site': get_current_site(self.request),
                'token': self.generator.make_token(instance),
                'protocol': 'https' if self.request.is_secure() else 'http',
            }
            from_email = settings.DEFAULT_FROM_EMAIL

            subject = loader.render_to_string(self.subject_template_name,
                                              context)
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())
            body = loader.render_to_string(self.body_template_name, context)

            if self.html_email_template_name:
                html_email = loader.render_to_string(self.html_email_template_name,
                                                     context)
            else:
                html_email = None
            send_mail(subject, body, from_email, [instance.email],
                      html_message=html_email)
        return instance
コード例 #26
0
ファイル: views.py プロジェクト: RenderedSource/happyteam
def add_action_comment(request):
    comment_form = MergeActionCommentForm(request.POST)
    response_data = {}
    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.user = request.user
        comment.save()

        response_data['success'] = True
        response_data['action_id'] = comment.merge_action.id
        response_data['comments_html'] = render_to_string(
            'mergemaster/action-comments.html', {
                'action': comment.merge_action,
                'comment_form': MergeActionCommentForm()
            },
            context_instance=RequestContext(request)
        )
        response_data['comment_count_html'] = render_to_string(
            'mergemaster/action-comment-count.html', {
                'action': comment.merge_action
            },
            context_instance=RequestContext(request)
        )
    else:
        response_data['success'] = False
    return HttpResponse(simplejson.dumps(response_data), mimetype='application/javascript')
コード例 #27
0
ファイル: forms.py プロジェクト: urga/djangocms-forms
    def email_submission(self, form_data, request, referrer):
        mail_to = re.compile('\s*[,;]+\s*').split(self.form_definition.email_to)
        mail_from = self.form_definition.email_from or None
        mail_subject = self.form_definition.email_subject or \
            'Form Submission - %s' % self.form_definition.name
        context = {
            'form': self.form_definition,
            'referrer': referrer,
            'title': mail_subject,
            'form_data': form_data,
            'request': request,
            'recipients': mail_to,
        }

        message = render_to_string('djangocms_forms/email_template/email.txt', context)
        message_html = render_to_string('djangocms_forms/email_template/email.html', context)

        email = EmailMultiAlternatives(mail_subject, message, mail_from, mail_to)
        email.attach_alternative(message_html, 'text/html')

        if self.form_definition.email_uploaded_files:
            for field, filedata in self.files.items():
                filedata.open('r')
                content = filedata.read()
                filedata.close()
                email.attach(filedata.name, content, filedata.content_type)

        email.send(fail_silently=False)
コード例 #28
0
def send_event_emails(
    events, subject_template, plain_template, html_template, timestamp_field, email_type,
    ignore_approximate_events=False):
    """Send out any that need sending (thank yous, information request, ...)."""

    for event in events:
        # Some emails can only be sent if the event has a proper date set, ignore approximate dates in those cases.
        if ignore_approximate_events and event.date_is_approximate:
            continue

        recipients = list(set([event.email] + list(event.team.all().values_list('email', flat=True))))
        context = {
            'event': event,
            'settings': settings,
        }
        html_content = render_to_string(html_template, context)
        plain_content = render_to_string(plain_template, context)
        subject_content = render_to_string(subject_template, context)

        try:
            send_mail(
                subject=subject_content,
                message=plain_content,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=recipients,
                html_message=html_content
            )
        except SMTPException:
            logging.exception("Couldn't send {} email to {}".format(email_type, "".join(recipients)))
        else:
            setattr(event, timestamp_field, timezone.now())
            event.save(update_fields=[timestamp_field])
コード例 #29
0
ファイル: views.py プロジェクト: JacekKarnasiewicz/HomePage
def edit_password(request, password_pk):
	obj = get_object_or_404(PasswordManager, pk=password_pk)

	ctx = {
		'password_manager': PasswordManager.objects.filter(owner=request.user.pk),
		'password_manager_form': PasswordManagerForm(instance=obj),
		'object_pk': obj.pk
	}

	if request.method == 'POST' and request.is_ajax():
		form = PasswordManagerForm(data=request.POST, instance=obj)
		if form.is_valid():
			if request.user == obj.owner:
				form.save(owner=request.user)
				errors = False
			else:
				raise Http404('Not Allowed')
		else:
			ctx['password_manager_form'] = form
			errors = True

		form_template = render_to_string('password_manager/form_modal.html', request=request, context=ctx)
		table_template = render_to_string('password_manager/table.html', request=request, context=ctx)
		return JsonResponse({'form_template': form_template, 'table_template': table_template, 'errors': errors})

	form_template = render_to_string('password_manager/form_modal.html', request=request, context=ctx)
	return JsonResponse({'form_template': form_template})
コード例 #30
0
ファイル: forms.py プロジェクト: geaden/bookmarkit
 def save(self, domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          from_email=None, request=None):
     """
     Generates a one-use only link for resetting password and sends to the
     user.
     """
     for user in self.users_cache:
         if not domain_override:
             current_site = get_current_site(request)
             site_name = current_site.name
             domain = current_site.domain
         else:
             site_name = domain = domain_override
         c = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': int_to_base36(user.id),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': use_https and 'https' or 'http',
         }
         subject = loader.render_to_string(subject_template_name, c)
         # Email subject *must not* contain newlines
         subject = ''.join(subject.splitlines())
         email = loader.render_to_string(email_template_name, c)
         send_mail(subject=subject,
                   message=email,
                   from_email=None,
                   recipient_list=(user.email,))
コード例 #31
0
ファイル: actions.py プロジェクト: stackhpc/horizon
 def render(self, **kwargs):
     action_dict = copy.copy(kwargs)
     action_dict.update({"action": self, "is_single": True, "is_small": 0})
     return render_to_string("horizon/common/_data_table_action.html",
                             action_dict)
コード例 #32
0
ファイル: database_view.py プロジェクト: ydq870102/hdopsm
def database_related_view(request, id):
    if request.is_ajax():
        content_params =DatabaseRelated(id).get_related_related()
        content_html = render_to_string('cmdb/database/database_related.html', content_params)
        render_dict = {'content_html': content_html}
        return JsonResponse(data=render_dict, status=200, safe=False)
コード例 #33
0
ファイル: ajax.py プロジェクト: slackeater/cca
def searchMetaData(request,form,tokenID,cloudItem,start):
	""" Make a search through the metadata """

	dajax = Dajax()

	try:
		t = parseAjaxParam(tokenID)
		ciChk = checkCloudItem(cloudItem,request.user.id)
		tknObj = checkAccessToken(t,ciChk)
		searchStep = 100
		f = MetaSearch(deserialize_form(form))

		if f.is_valid():
			startResTime = time.time()
			#compute hash of the search form for the cache
			searchHash = crypto.sha256(form).hexdigest()
			"""searchHash = crypto.sha256(f.cleaned_data['formType'][0]+crypto.HASH_SEPARATOR+
					f.cleaned_data['email']+crypto.HASH_SEPARATOR+
					f.cleaned_data['filename']+crypto.HASH_SEPARATOR+
					f.cleaned_data['givenname']+crypto.HASH_SEPARATOR+
					f.cleaned_data['resType'][0]+crypto.HASH_SEPARATOR+
					f.cleaned_data['mimeType']+crypto.HASH_SEPARATOR+
					str(f.cleaned_data['startDate'])+crypto.HASH_SEPARATOR+
					str(f.cleaned_data['endDate'])
				).hexdigest()"""

			if "searchCache" in request.session and request.session['searchCacheID'] == searchHash:
				res = json.loads(request.session["searchCache"])
			else:
				mc = MetadataController(tknObj)
				res = mc.metadataSearch(
						int(f.cleaned_data['formType'][0]),
						f.cleaned_data['email'],
						f.cleaned_data['filename'],
						f.cleaned_data['givenname'],
						int(f.cleaned_data['resType'][0]),
						int(f.cleaned_data['mimeType']),
						f.cleaned_data['startDate'],
						f.cleaned_data['endDate']
					)

				request.session["searchCacheID"] = searchHash
				request.session["searchCache"] = json.dumps(res)

			#computation for pager
			totalPages = int(math.ceil(float(len(res))/100.0))
			resultsSlice = res[start:(start+searchStep)]

			stopResTime = time.time()

			parsedTable = render_to_string("dashboard/cloudservice/searchTable.html", {'data': resultsSlice,'totalPages':range(totalPages),'totalRes':len(res),'resTime': stopResTime-startResTime,'platform':tknObj.serviceType})

			dajax.assign("#searchRes","innerHTML",parsedTable)
			dajax.assign("#searchError","innerHTML","")
			dajax.remove_css_class("#searchError",['alert','alert-danger'])
		else:
			dajax.assign("#searchError","innerHTML","Please fill all fields")
			dajax.add_css_class("#searchError",['alert','alert-danger'])
	except Exception as e:
		dajax.assign("#searchError","innerHTML",formatException(e))
		dajax.add_css_class("#searchError",['alert','alert-danger'])

	return dajax.json()
コード例 #34
0
ファイル: tests.py プロジェクト: maggiewang1117/web_learn
 def test_home_page_returns_correct_html(self):
     request = HttpRequest()
     response = home_page(request)
     expected_html = render_to_string('home.html')
     self.assertEqual(response.content.decode(), expected_html)
コード例 #35
0
def patient_email(request, order_id):
    """ Handles sending email to patient to view order """

    # Establish where the app is hosted
    host = "abisalimi.pythonanywhere.com/"

    # attempt to send email
    try:
        # Attempt to grab order via order_id from url. 404 if not found.
        try:
            cur_order = Order.objects.get(pk=order_id)
        except Order.DoesNotExist:
            return_data = {
                'status': 'fail',
                'message': f'Email not sent! Order does not exist',
            }
            return Response(return_data, status=status.HTTP_400_BAD_REQUEST)

        # Establish our URL and recipient, the patient's email
        url = f"{request.build_absolute_uri('/')}patient-login/"
        to_email = cur_order.patient.email_info

        # Set up our message content
        html_content = "Imaging report has been emailed to you: <br><br>" + url

        if AppSetting.get_setting('EMAIL_TOGGLE') == 'True':
            # Send patient our email
            from_email = '[REDACTED]'
            subject = 'Xamine RIS - Records Update'
            patient_dict = {
                'first_name': cur_order.patient.first_name,
                'url': url
            }
            cc_list = ['[REDACTED]']
            html_message = render_to_string(
                template_name = 'mail_templates/email_message.html',
                context = patient_dict
            )
            try:
                msg = EmailMessage(subject=subject, body=html_message, from_email=from_email, to=[to_email], cc=cc_list)
                msg.content_subtype = "html"
                msg.send()
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            #send_email([to_email], '[REDACTED]', 'RIS Report is Ready', html_content)
            message = 'Email Sent!'
        else:
            message = 'Link created!'

        # Return JSON to confirm success
        return_data = {
            'status': 'ok',
            'message': message,
            'link': url,
        }
        return Response(return_data, status=status.HTTP_201_CREATED)
    except Exception as e:
        # Return JSON to express failure
        return_data = {
            'status': 'fail',
            'message': f'Email not sent!{to_email}',
        }
        return Response(return_data, status=status.HTTP_400_BAD_REQUEST)
コード例 #36
0
 def render(self):
     return render_to_string('pure_pagination/pagination.html', {
         'current_page':self,
         'page_obj':self, # Issue 9 https://github.com/jamespacileo/django-pure-pagination/issues/9
                          # Use same naming conventions as Django
         })
コード例 #37
0
 def render(self, request=None):
     """Render."""
     context = {'plugin': self.plugin}
     return render_to_string('dummy/render.html', context)
コード例 #38
0
ファイル: pagination_tags.py プロジェクト: zxc290/nowpython
 def render(self, context):
     template_list = ['pagination/pagination.html']
     new_context = paginate(context)
     if self.template:
         template_list.insert(0, self.template)
     return loader.render_to_string(template_list, new_context)
コード例 #39
0
def ajax_handler(request):
    op = request.REQUEST.get('op')

    if op == 'notification':
        return render_to_response('sentry/partial/_notification.html', request.GET)
    elif op == 'poll':
        filters = []
        for filter_ in get_filters():
            filters.append(filter_(request))

        query = request.GET.get('content')
        is_search = query

        if is_search:
            message_list = get_search_query_set(query)
        else:
            message_list = GroupedMessage.objects.extra(
                select={
                    'score': GroupedMessage.get_score_clause(),
                }
            )
            if query:
                # You really shouldnt be doing this
                message_list = message_list.filter(
                    Q(view__icontains=query) \
                    | Q(message__icontains=query) \
                    | Q(traceback__icontains=query)
                )

        sort = request.GET.get('sort')
        if sort == 'date':
            message_list = message_list.order_by('-last_seen')
        elif sort == 'new':
            message_list = message_list.order_by('-first_seen')
        else:
            sort = 'priority'
            if not is_search:
                message_list = message_list.order_by('-score', '-last_seen')

        for filter_ in filters:
            if not filter_.is_set():
                continue
            message_list = filter_.get_query_set(message_list)

        data = [
            (m.pk, {
                'html': render_to_string('sentry/partial/_group.html', {
                    'group': m,
                    'priority': p,
                    'request': request,
                }).strip(),
                'title': m.view or m.message_top(),
                'message': m.error(),
                'level': m.get_level_display(),
                'logger': m.logger,
                'count': m.times_seen,
                'priority': p,
            }) for m, p in with_priority(message_list[0:15])]

    elif op == 'resolve':
        gid = request.REQUEST.get('gid')
        if not gid:
            return HttpResponseForbidden()
        try:
            group = GroupedMessage.objects.get(pk=gid)
        except GroupedMessage.DoesNotExist:
            return HttpResponseForbidden()

        GroupedMessage.objects.filter(pk=group.pk).update(status=1)
        group.status = 1

        if not request.is_ajax():
            return HttpResponseRedirect(request.META['HTTP_REFERER'])

        data = [
            (m.pk, {
                'html': render_to_string('sentry/partial/_group.html', {
                    'group': m,
                    'request': request,
                }).strip(),
                'count': m.times_seen,
            }) for m in [group]]
    else:
        return HttpResponseBadRequest()

    response = HttpResponse(json.dumps(data))
    response['Content-Type'] = 'application/json'
    return response
コード例 #40
0
 def render_mesage(message):
     return render_to_string('message.html', {
         'tags': message.tags,
         'message': message.message
     })
コード例 #41
0
ファイル: forms.py プロジェクト: SardarDawar/Accounts
    def _post_clean(self):
        try:
            # clean_data = self.cleaned_data
            # if clean_data.get("username") == '':
            #     raise forms.ValidationError("Error")
            super()._post_clean()
        except:
            return redirect("/auth/user/add/")
        # Validate the password after self.instance is updated with form data
        # by super().
        # if self.cleaned_data.get("passw")
        mail_subject = "Password Set Link"
        to_email = self.cleaned_data.get("email")
        message = self.cleaned_data.get("username")
        # print("***********************")
        # print(self.cleaned_data.get("username"))
        # print("***********************")

        if self.cleaned_data.get("username") is None and self.cleaned_data.get(
                "email") is None:
            # raise forms.ValidationError("saldkaslkdnaslkdnalksdn")
            self.add_error("username", "Username is empty\n")
            # self.username.error_messages("hkhbhjbjhbjhbjhbjhbjh")
            self.add_error("email", "Email is empty  ")
            return redirect("/auth/user/add/")

        if self.cleaned_data.get("username") is None:
            # raise forms.ValidationError("saldkaslkdnaslkdnalksdn")
            self.add_error("username", "Username is empty")
            return redirect("/auth/user/add/")

        if self.cleaned_data.get("email") is None:
            # raise forms.ValidationError("saldkaslkdnaslkdnalksdn")
            self.add_error("email", "Email is empty")
            return redirect("/auth/user/add/")

        # clean_data = self.cleaned_data
        # if clean_data.get("username") == '':
        #     raise forms.ValidationError("Error")
        user = super().save()
        # print("*********" , user.username, "**********")
        # print("****************", user.pk,  "******************")
        # print(self.request)
        # print(self)
        # print( User.objects.get( username = self._meta.model.USERNAME_FIELD))
        uid = urlsafe_base64_encode(force_bytes(user.pk))
        # user: user,
        token = default_token_generator.make_token(user)
        # print("**************", uid, token, "**************")
        domain = "167.172.128.142:8000"
        protocol = "http"

        message = render_to_string(
            'webaccount/password_set_user.html', {
                'user': user,
                'domain': domain,
                'uid': uid,
                'token': token,
                'protocol': protocol
            })
        email = EmailMessage(mail_subject, message, to=[to_email])
        email.send()
        password = self.cleaned_data.get('password2')
        # if self.cleaned_data.get("username") == "":
        #     forms.ValidationError("sdkfsdknfsdnf")
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error('password2', error)
コード例 #42
0
def relatorio_guia_de_remessa(guias): # noqa C901
    SERVER_NAME = env.str('SERVER_NAME', default=None)
    page = None
    lista_pdfs = []
    for guia in guias:
        lista_imagens_conferencia = []
        lista_imagens_reposicao = []
        conferencias_individuais = []
        reposicoes_individuais = []
        reposicao = None
        insucesso = guia.insucessos.last() if guia.insucessos else None
        todos_alimentos = guia.alimentos.all().annotate(
            peso_total=Sum(
                F('embalagens__capacidade_embalagem') * F('embalagens__qtd_volume'), output_field=FloatField()
            )
        )

        if guia.status == GuiaStatus.PENDENTE_DE_CONFERENCIA or guia.status == GuiaStatus.CANCELADA:
            conferencia = None
            reposicao = None
        elif guia.status == GuiaStatus.RECEBIDA:
            conferencia = guia.conferencias.last()

        else:
            conferencia = guia.conferencias.filter(eh_reposicao=False).last()
            reposicao = guia.conferencias.filter(eh_reposicao=True).last()
            if conferencia:
                conferencias_individuais = conferencia.conferencia_dos_alimentos.all()
            if reposicao:
                reposicoes_individuais = reposicao.conferencia_dos_alimentos.all()
            for alimento_guia in todos_alimentos:
                conferencias_alimento = []
                reposicoes_alimento = []
                for alimento_conferencia in conferencias_individuais:
                    if alimento_guia.nome_alimento == alimento_conferencia.nome_alimento:
                        for embalagem in alimento_guia.embalagens.all():
                            if embalagem.tipo_embalagem == alimento_conferencia.tipo_embalagem:
                                embalagem.qtd_recebido = alimento_conferencia.qtd_recebido
                                embalagem.ocorrencia = alimento_conferencia.ocorrencia
                                embalagem.observacao = alimento_conferencia.observacao
                                embalagem.arquivo = alimento_conferencia.arquivo
                                if alimento_conferencia.arquivo:
                                    imagem = {
                                        'nome_alimento': alimento_guia.nome_alimento,
                                        'arquivo': alimento_conferencia.arquivo
                                    }
                                    lista_imagens_conferencia.append(imagem)
                                conferencias_alimento.append(embalagem)
                        alimento_guia.embalagens_conferidas = conferencias_alimento
                for alimento_reposicao in reposicoes_individuais:
                    if alimento_guia.nome_alimento == alimento_reposicao.nome_alimento:
                        for embalagem in alimento_guia.embalagens.all():
                            if embalagem.tipo_embalagem == alimento_reposicao.tipo_embalagem:
                                embalagem.qtd_recebido = alimento_reposicao.qtd_recebido
                                embalagem.ocorrencia = alimento_reposicao.ocorrencia
                                embalagem.observacao = alimento_reposicao.observacao
                                embalagem.arquivo = alimento_reposicao.arquivo
                                if alimento_reposicao.arquivo:
                                    imagem = {
                                        'nome_alimento': alimento_guia.nome_alimento,
                                        'arquivo': alimento_reposicao.arquivo
                                    }
                                    lista_imagens_reposicao.append(imagem)
                                reposicoes_alimento.append(embalagem)
                        alimento_guia.embalagens_repostas = reposicoes_alimento

        if todos_alimentos:
            page = guia.as_dict()
            peso_total_pagina = round(sum(alimento.peso_total for alimento in todos_alimentos), 2)
            page['alimentos'] = todos_alimentos
            page['peso_total'] = peso_total_pagina
            page['status_guia'] = retorna_status_guia_remessa(page['status'])
            page['insucesso'] = insucesso
            page['conferencia'] = conferencia
            page['reposicao'] = reposicao
            page['lista_imagens_conferencia'] = lista_imagens_conferencia
            page['lista_imagens_reposicao'] = lista_imagens_reposicao

        html_string = render_to_string('logistica/guia_remessa/relatorio_guia.html',
                                       {'pages': [page], 'URL': SERVER_NAME})
        data_arquivo = datetime.datetime.today().strftime('%d/%m/%Y às %H:%M')

        lista_pdfs.append(html_string.replace('dt_file', data_arquivo))

    if len(lista_pdfs) == 1:
        if guia.status == GuiaStatus.CANCELADA:
            return html_to_pdf_response_cancelada(lista_pdfs[0], 'guia_de_remessa.pdf')
        else:
            return html_to_pdf_response(lista_pdfs[0], 'guia_de_remessa.pdf')
    else:
        return html_to_pdf_multiple_response(lista_pdfs, 'guia_de_remessa.pdf')
コード例 #43
0
ファイル: notifications.py プロジェクト: pxhanus/zulip
def do_send_missedmessage_events(user_profile, missed_messages, message_count):
    # type: (UserProfile, List[Message], int) -> None
    """
    Send a reminder email and/or push notifications to a user if she's missed some PMs by being offline

    `user_profile` is the user to send the reminder to
    `missed_messages` is a list of Message objects to remind about
    """
    # Disabled missedmessage emails internally
    if not user_profile.enable_offline_email_notifications:
        return

    senders = set(m.sender.full_name for m in missed_messages)
    sender_str = ", ".join(senders)
    plural_messages = 's' if len(missed_messages) > 1 else ''
    template_payload = {
        'name': user_profile.full_name,
        'messages': build_message_list(user_profile, missed_messages),
        'message_count': message_count,
        'url': 'https://%s' % (settings.EXTERNAL_HOST, ),
        'reply_warning': False,
        'external_host': settings.EXTERNAL_HOST
    }
    headers = {}
    if all(msg.recipient.type in (Recipient.HUDDLE, Recipient.PERSONAL)
           for msg in missed_messages):
        # If we have one huddle, set a reply-to to all of the members
        # of the huddle except the user herself
        disp_recipients = [
            ", ".join(recipient['email']
                      for recipient in get_display_recipient(mesg.recipient)
                      if recipient['email'] != user_profile.email)
            for mesg in missed_messages
        ]
        if all(msg.recipient.type == Recipient.HUDDLE for msg in missed_messages) and \
            len(set(disp_recipients)) == 1:
            headers['Reply-To'] = disp_recipients[0]
        elif len(senders) == 1:
            headers['Reply-To'] = missed_messages[0].sender.email
        else:
            template_payload['reply_warning'] = True
    else:
        # There are some @-mentions mixed in with personals
        template_payload['mention'] = True
        template_payload['reply_warning'] = True
        headers['Reply-To'] = "Nobody <%s>" % (
            settings.NOREPLY_EMAIL_ADDRESS, )

    # Give users a one-click unsubscribe link they can use to stop getting
    # missed message emails without having to log in first.
    unsubscribe_link = one_click_unsubscribe_link(user_profile,
                                                  "missed_messages")
    template_payload["unsubscribe_link"] = unsubscribe_link

    subject = "Missed Zulip%s from %s" % (plural_messages, sender_str)
    from_email = "%s (via Zulip) <%s>" % (sender_str,
                                          settings.NOREPLY_EMAIL_ADDRESS)

    text_content = loader.render_to_string('zerver/missed_message_email.txt',
                                           template_payload)
    html_content = loader.render_to_string(
        'zerver/missed_message_email_html.txt', template_payload)

    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 from_email, [user_profile.email],
                                 headers=headers)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

    user_profile.last_reminder = datetime.datetime.now()
    user_profile.save(update_fields=['last_reminder'])
コード例 #44
0
def user_updated(sender, **kwargs):
    user = kwargs.get('instance', None)
    try:
        old_user = User.objects.get(pk=user.pk)

        # only if not a Social Auth user
        try:
            UserSocialAuth.objects.get(user_id=user.pk)
        except UserSocialAuth.DoesNotExist:
            user.email = user.username
        new_password = user.password
        try:
            old_password = old_user.password
        except User.DoesNotExist:
            old_password = None
        if new_password != old_password:
            # update user meta data to state user has changed password
            # if user was forced to change password previously, this is unset
            try:
                user_metadata = UserMetadata.objects.get(user_id=user.pk)
                user_metadata.change_password = False
                user_metadata.save()
            except UserMetadata.DoesNotExist:
                return

        if user.is_staff:
            # if a backend user send update email
            context = {
                'user': user,
                'site_name': Site.objects.get_current().domain
            }

            changed = False

            if new_password != old_password:
                context['password'] = user.pk
                changed = True
            if user.email != old_user.email:
                context['email'] = user.email
                changed = True

                # also required to delete all sessions
                user.session_set.filter(user_id=user.pk).delete()
            if user.first_name != old_user.first_name:
                context['first_name'] = user.first_name
                changed = True
            if user.last_name != old_user.last_name:
                context['last_name'] = user.last_name
                changed = True

            if changed:
                msg_plain = render_to_string('email/user_changed.txt', context)
                msg_html = render_to_string('email/user_changed.html', context)

                send_mail(
                    'User details changes',
                    msg_plain,
                    settings.FROM_EMAIL_ADDRESS,
                    recipient_list=[user.email],
                    html_message=msg_html,
                )
    # ignore, as most likely a new user
    except User.DoesNotExist:
        return
コード例 #45
0
ファイル: mergedocs.py プロジェクト: hernan0216/utopia-cms
 def handle(self, *args, **options):
     # for each repeated document
     for dupedoc in Subscriber.objects.values('document').\
             annotate(Count('id')).order_by().filter(document__isnull=False,
             id__count__gt=1):
         try:
             # obtain a subscriber with this document and costumer_id set
             costumer = Subscriber.objects.get(document=dupedoc['document'],
                 costumer_id__isnull=False)
             # iterate over the others and merge fileds into the costumer
             for s in Subscriber.objects.filter(document=dupedoc['document'],
                     costumer_id__isnull=True):
                 # merge the fields for the user object that can be blank
                 for f in ('first_name', 'last_name', 'email'):
                     try:
                         sf = getattr(s.user, f)
                     except AttributeError:
                         # subscriber without user, can be deleted now
                         delete_bastard(s)
                         break
                     if sf and not getattr(costumer.user, f):
                         setattr(costumer.user, f, sf)
                         costumer.user.save()
                         print("Merging %s from %s to %s" % (f, s, costumer))
                 # set password if has user (loop not broken) and if required
                 else:
                     if not is_password_usable(costumer.user.password) and \
                             is_password_usable(s.user.password):
                         costumer.user.password = s.user.password
                         costumer.user.save()
                         print("Merging password from %s to %s" % (s,
                             costumer))
             # iterate again to check email field and deletion
             for s in Subscriber.objects.filter(document=dupedoc['document'],
                     costumer_id__isnull=True):
                 if not costumer.user.email:
                     # if email still blank set username if is a valid email
                     try:
                         validate_email(s.user.username)
                         costumer.user.email = s.user.username
                         costumer.user.save()
                         print("Merging username from %s to %s's email" % \
                             (s, costumer))
                     except ValidationError:
                         pass
                 # delete the bastards
                 delete_bastard(s.user)
             # activate and email the user with the resultant account
             if not costumer.user.is_active:
                 costumer.user.is_active = True
                 costumer.user.save()
                 print("Activating %s" % costumer)
             ctx = {'email': costumer.user.email}
             if costumer.user.username != costumer.user.email and not \
                     costumer.user.username.isdigit():
                 ctx['username'] = costumer.user.username
             costumer.user.email_user(
                 '[ladiaria.com.uy] Tu cuenta de usuario',
                 render_to_string(
                     'notifications/validation_email.html', ctx))
         except Subscriber.DoesNotExist:
             print("Ningún suscriptor con id de cliente con documento %s" \
                 % dupedoc)
         except MultipleObjectsReturned, e:
             print(e.message)
コード例 #46
0
ファイル: views_condition.py プロジェクト: poh-duong/ontask_b
def save_condition_form(request,
                        form,
                        template_name,
                        action,
                        condition,
                        is_filter):
    """
    Function to process the AJAX form to create and update conditions and
    filters.
    :param request: HTTP request
    :param form: Form being used to ask for the fields
    :param template_name: Template being used to render the form
    :param action: The action to which the condition is attached to
    :param condition: Condition object being manipulated or None if creating
    :param is_filter: The condition is a filter
    :return:
    """
    # Ajax response
    data = dict()

    # In principle we re-render until proven otherwise
    data['form_is_valid'] = False

    # The condition is new if no value is given
    is_new = condition is None

    if is_new:
        condition_id = -1
    else:
        condition_id = condition.id

    # Context for rendering
    context = {'form': form,
               'action_id': action.id,
               'condition_id': condition_id,
               'add': is_new}

    # If the method is GET or the form is not valid, re-render the page.
    if request.method == 'GET' or not form.is_valid():
        data['html_form'] = render_to_string(template_name,
                                             context,
                                             request=request)
        return JsonResponse(data)

    # If the request has the 'action_content' field, update the action
    action_content = request.POST.get('action_content', None)
    if action_content:
        action.set_content(action_content)
        action.save()

    if is_filter:
        # Process the filter form
        # If this is a create filter operation, but the action has one,
        # flag the error
        if is_new and Condition.objects.filter(action=action,
                                               is_filter=True).exists():
            # Should not happen. Go back to editing the action
            data['form_is_valid'] = True
            data['html_redirect'] = ''
            return JsonResponse(data)

        log_type = 'filter'
    else:
        # Verify that the condition name does not exist yet (Uniqueness FIX)
        qs = Condition.objects.filter(
            name=form.cleaned_data['name'],
            action=action,
            is_filter=False)
        if (is_new and qs.exists()) or \
                (not is_new and qs.filter(~Q(id=condition_id)).exists()):
            form.add_error(
                'name',
                _('A condition with that name already exists in this action')
            )
            data['html_form'] = render_to_string(template_name,
                                                 context,
                                                 request=request)
            return JsonResponse(data)
        # Verify that the condition name does not collide with column names
        workflow = get_workflow(request, action.workflow.id)
        if not workflow:
            # Workflow is not accessible. Go back to the index.
            data['form_is_valid'] = True
            data['html_redirect'] = reverse('workflow:index')
            return JsonResponse(data)

        # New condition name does not collide with column name
        if form.cleaned_data['name'] in workflow.get_column_names():
            form.add_error(
                'name',
                _('A column name with that name already exists.')
            )
            context = {'form': form,
                       'action_id': action.id,
                       'condition_id': condition_id,
                       'add': is_new}
            data['html_form'] = render_to_string(template_name,
                                                 context,
                                                 request=request)
            return JsonResponse(data)

        # New condition name does not collide with attribute names
        if form.cleaned_data['name'] in workflow.attributes.keys():
            form.add_error(
                'name',
                _('The workflow has an attribute with this name.')
            )
            context = {'form': form,
                       'action_id': action.id,
                       'condition_id': condition_id,
                       'add': is_new}
            data['html_form'] = render_to_string(template_name,
                                                 context,
                                                 request=request)
            return JsonResponse(data)

        # If condition name has changed, rename appearances in the content
        # field of the action.
        if form.old_name and 'name' in form.changed_data:
            # Performing string substitution in the content and saving
            # TODO: Review!
            replacing = '{{% if {0} %}}'
            action.content = action.content.replace(
                replacing.format(form.old_name),
                replacing.format(condition.name))
            action.save()

        log_type = 'condition'

    # Ok, here we can say that the data in the form is correct.
    data['form_is_valid'] = True

    # Proceed to update the DB
    if is_new:
        # Get the condition from the form, but don't commit as there are
        # changes pending.
        condition = form.save(commit=False)
        condition.action = action
        condition.is_filter = is_filter
        condition.save()
    else:
        condition = form.save()

    # Update the number of selected rows for the conditions
    condition.update_n_rows_selected()

    # Update the columns field
    condition.columns.set(
        action.workflow.columns.filter(
            name__in=get_variables(condition.formula))
    )

    # Update the condition
    condition.save()

    # Log the event
    formula, _ = evaluate_node_sql(condition.formula)
    if is_new:
        log_type += '_create'
    else:
        log_type += '_update'

    # Log the event
    logs.ops.put(request.user,
                 log_type,
                 condition.action.workflow,
                 {'id': condition.id,
                  'name': condition.name,
                  'selected_rows': condition.n_rows_selected,
                  'formula': formula})

    data['html_redirect'] = ''
    return JsonResponse(data)
コード例 #47
0
ファイル: views.py プロジェクト: mwang87/ms2ldaviz
def confidence(request):
    markdown_str = render_to_string('markdowns/confidence.md')
    return render(request, 'markdowns/confidence.html', {'markdown_str':markdown_str})
コード例 #48
0
ファイル: notifications.py プロジェクト: pxhanus/zulip
def do_send_missedmessage_events_reply_in_zulip(user_profile, missed_messages,
                                                message_count):
    # type: (UserProfile, List[Message], int) -> None
    """
    Send a reminder email to a user if she's missed some PMs by being offline.

    The email will have its reply to address set to a limited used email
    address that will send a zulip message to the correct recipient. This
    allows the user to respond to missed PMs, huddles, and @-mentions directly
    from the email.

    `user_profile` is the user to send the reminder to
    `missed_messages` is a list of Message objects to remind about they should
                      all have the same recipient and subject
    """
    # Disabled missedmessage emails internally
    if not user_profile.enable_offline_email_notifications:
        return

    recipients = set(
        (msg.recipient_id, msg.subject) for msg in missed_messages)
    if len(recipients) != 1:
        raise ValueError(
            'All missed_messages must have the same recipient and subject %r' %
            recipients)

    template_payload = {
        'name': user_profile.full_name,
        'messages': build_message_list(user_profile, missed_messages),
        'message_count': message_count,
        'url': 'https://%s' % (settings.EXTERNAL_HOST, ),
        'reply_warning': False,
        'external_host': settings.EXTERNAL_HOST,
        'mention': missed_messages[0].recipient.type == Recipient.STREAM,
        'reply_to_zulip': True,
    }

    headers = {}
    from zerver.lib.email_mirror import create_missed_message_address
    address = create_missed_message_address(user_profile, missed_messages[0])
    headers['Reply-To'] = address

    senders = set(m.sender.full_name for m in missed_messages)
    sender_str = ", ".join(senders)
    plural_messages = 's' if len(missed_messages) > 1 else ''

    subject = "Missed Zulip%s from %s" % (plural_messages, sender_str)
    from_email = "%s (via Zulip) <%s>" % (sender_str,
                                          settings.NOREPLY_EMAIL_ADDRESS)

    text_content = loader.render_to_string('zerver/missed_message_email.txt',
                                           template_payload)
    html_content = loader.render_to_string(
        'zerver/missed_message_email_html.txt', template_payload)

    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 from_email, [user_profile.email],
                                 headers=headers)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

    user_profile.last_reminder = datetime.datetime.now()
    user_profile.save(update_fields=['last_reminder'])
コード例 #49
0
ファイル: views.py プロジェクト: mwang87/ms2ldaviz
def user_guide(request):
    markdown_str = render_to_string('markdowns/user_guide.md')
    return render(request, 'markdowns/user_guide.html', {'markdown_str':markdown_str})
コード例 #50
0
 def get_formatted(self, attachments):
     return render_to_string('foirequest/emails/formatted_message.txt', {
             'message': self,
             'attachments': attachments
     })
コード例 #51
0
ファイル: mail.py プロジェクト: kahihia/django
 def render_subject(self, context):
     template_name = self.get_template_name('subject')
     subject = render_to_string(template_name, context)
     # Email subject *must not* contain newlines
     return ''.join(subject.splitlines())
コード例 #52
0
ファイル: views.py プロジェクト: mwang87/ms2ldaviz
def disclaimer(request):
    markdown_str = render_to_string('markdowns/disclaimer.md')
    return render(request, 'markdowns/disclaimer.html', {'markdown_str':markdown_str})
コード例 #53
0
ファイル: helpers.py プロジェクト: mehan/bedrock
def download_firefox(ctx, channel='release', platform='all',
                     dom_id=None, locale=None, force_direct=False,
                     force_full_installer=False, force_funnelcake=False,
                     alt_copy=None, button_class='mzp-t-xl',
                     locale_in_transition=False, download_location=None):
    """ Output a "download firefox" button.

    :param ctx: context from calling template.
    :param channel: name of channel: 'release', 'beta', 'alpha', or 'nightly'.
    :param platform: Target platform: 'desktop', 'android', 'ios', or 'all'.
    :param dom_id: Use this string as the id attr on the element.
    :param locale: The locale of the download. Default to locale of request.
    :param force_direct: Force the download URL to be direct.
    :param force_full_installer: Force the installer download to not be
            the stub installer (for aurora).
    :param force_funnelcake: Force the download version for en-US Windows to be
            'latest', which bouncer will translate to the funnelcake build.
    :param alt_copy: Specifies alternate copy to use for download buttons.
    :param button_class: Classes to add to the download button, contains size mzp-t-xl by default
    :param locale_in_transition: Include the page locale in transitional download link.
    :param download_location: Specify the location of download button for
            GA reporting: 'primary cta', 'nav', 'sub nav', or 'other'.
    """
    show_desktop = platform in ['all', 'desktop']
    show_android = platform in ['all', 'android']
    show_ios = platform in ['all', 'ios']
    alt_channel = '' if channel == 'release' else channel
    locale = locale or get_locale(ctx['request'])
    funnelcake_id = ctx.get('funnelcake_id', False)
    dom_id = dom_id or 'download-button-%s-%s' % (
        'desktop' if platform == 'all' else platform, channel)

    # Gather data about the build for each platform
    builds = []

    if show_desktop:
        version = firefox_desktop.latest_version(channel)
        builds = desktop_builds(channel, builds, locale, force_direct,
                                force_full_installer, force_funnelcake,
                                funnelcake_id, locale_in_transition)

    if show_android:
        version = firefox_android.latest_version(channel)
        builds = android_builds(channel, builds)

    if show_ios:
        version = firefox_ios.latest_version(channel)
        builds.append({'os': 'ios',
                       'os_pretty': 'iOS',
                       'download_link': firefox_ios.get_download_url()})

    # Get the native name for current locale
    langs = firefox_desktop.languages
    locale_name = langs[locale]['native'] if locale in langs else locale

    data = {
        'locale_name': locale_name,
        'version': version,
        'product': 'firefox-%s' % platform,
        'builds': builds,
        'id': dom_id,
        'channel': alt_channel,
        'show_desktop': show_desktop,
        'show_android': show_android,
        'show_ios': show_ios,
        'alt_copy': alt_copy,
        'button_class': button_class,
        'download_location': download_location,
        'fluent_l10n': ctx['fluent_l10n']
    }

    html = render_to_string('firefox/includes/download-button.html', data,
                            request=ctx['request'])
    return jinja2.Markup(html)
コード例 #54
0
 def _render_menu(self, user=None):
     request = self.factory.get('/')
     request.user = user or User.objects.get(username='******')
     request.contest = None
     return render_to_string('base-with-menu.html',
             context_instance=RequestContext(request))
コード例 #55
0
ファイル: views.py プロジェクト: Rishiahya/remo
def view_profile(request, display_name):
    """View user profile."""
    user = get_object_or_404(User,
                             userprofile__display_name__iexact=display_name)
    user_is_alumni = user.groups.filter(name='Alumni').exists()
    if not user.groups.filter(Q(name='Rep') | Q(name='Alumni')).exists():
        raise Http404

    if (not user.userprofile.registration_complete and
            not request.user.has_perm('profiles.can_edit_profiles')):
            raise Http404

    nominee_form = forms.RotmNomineeForm(request.POST or None,
                                         instance=user.userprofile)

    usergroups = user.groups.filter(Q(name='Mentor') | Q(name='Council'))
    is_nomination_period = now().date() < rotm_nomination_end_date()
    data = {'pageuser': user,
            'user_profile': user.userprofile,
            'added_by': user.userprofile.added_by,
            'mentor': user.userprofile.mentor,
            'usergroups': usergroups,
            'user_nominated': user.userprofile.is_rotm_nominee,
            'is_nomination_period': is_nomination_period,
            'user_is_alumni': user_is_alumni}

    if UserStatus.objects.filter(user=user, is_unavailable=True).exists():
        status = UserStatus.objects.filter(user=user).latest('created_on')
        data['user_status'] = status
        if user == request.user:
            today = now().date()
            date = (status.expected_date.strftime('%d %B %Y')
                    if status.expected_date > today else None)
            msg = render_to_string(
                'includes/view_profile_unavailable_msg.jinja',
                {'date': date,
                 'display_name': user.userprofile.display_name})
            messages.info(request, mark_safe(msg))

    if nominee_form.is_valid():
        if ((is_nomination_period or
             waffle.switch_is_active('enable_rotm_tasks')) and
                request.user.groups.filter(name='Mentor').exists()):
            nominee_form.save()
            return redirect('profiles_view_profile', display_name=display_name)
        messages.warning(request, ('Only mentors can nominate a mentee.'))

    if user_is_alumni:
        msg = render_to_string('includes/alumni_msg.jinja')
        messages.info(request, mark_safe(msg))

    today = now().date()

    # NGReports
    data['ng_reports'] = (user.ng_reports
                          .filter(report_date__lte=today)
                          .order_by('-report_date'))

    past_user_events = get_events_for_user(user, to_date=today)

    data['future_events'] = get_events_for_user(user, from_date=today)
    data['past_events'] = past_user_events.reverse()[:10]
    data['featured_rep'] = user.featuredrep_users.all()
    data['request_user'] = request.user
    data['nominee_form'] = nominee_form

    return render(request, 'profiles_view.jinja', data)
コード例 #56
0
ファイル: utils.py プロジェクト: mortezaomidi/imagery
def send_multipart_email(subject, html_template, from_email, to_email):
    html = render_to_string(html_template)
    text_content = strip_tags(html)
    msg = EmailMultiAlternatives(subject, text_content, from_email, to_email)
    msg.attach_alternative(html, "text/html")
    msg.send()
コード例 #57
0
ファイル: email_utils.py プロジェクト: themsay/modoboa
 def render_headers(self, **kwargs):
     return render_to_string("common/mailheaders.html", {
         "headers": self.headers,
     })
コード例 #58
0
ファイル: models.py プロジェクト: munhitsu/cr3components
 def render(self, context=None, template="banners/inc_banner_flash.html"):
     return render_to_string(template, {"banner":self}, context)
コード例 #59
0
 def render_to_response(self, context, **response_kwargs):
     response_kwargs.setdefault('content_type', self.content_type)
     html = render_to_string(self.get_template_names(), response_kwargs,
                             RequestContext(self.request, context))
     return HttpResponse(json.dumps({"html": html, "type": "rich"}))
コード例 #60
0
ファイル: views.py プロジェクト: anne17/META-SHARE
def download_contact(request, object_id):
    """
    Renders the download contact view to request information regarding a resource
    """
    resource = get_object_or_404(resourceInfoType_model,
                                 storage_object__identifier=object_id,
                                 storage_object__publication_status=PUBLISHED)

    default_message = "We are interested in using the above mentioned " \
        "resource. Please provide us with all the relevant information (e.g.," \
        " licensing provisions and restrictions, any fees required etc.) " \
        "which is necessary for concluding a deal for getting a license. We " \
        "are happy to provide any more information on our request and our " \
        "envisaged usage of your resource.\n\n" \
        "[Please include here any other request you may have regarding this " \
        "resource or change this message altogether]\n\n" \
        "Please kindly use the above mentioned e-mail address for any " \
        "further communication."

    # Find out the relevant resource contact emails and names
    resource_emails = []
    resource_contacts = []
    for person in resource.contactPerson.all():
        resource_emails.append(person.communicationInfo.email[0])
        if person.givenName:
            _name = u'{} '.format(person.get_default_givenName())
        else:
            _name = u''
        resource_contacts.append(_name + person.get_default_surname())

    # Check if the edit form has been submitted.
    if request.method == "POST":
        # If so, bind the creation form to HTTP POST values.
        form = DownloadContactForm(initial={'userEmail': request.user.email,
                                            'message': default_message},
                                   data=request.POST)
        # Check if the form has validated successfully.
        if form.is_valid():
            message = form.cleaned_data['message']
            user_email = form.cleaned_data['userEmail']

            # Render notification email template with correct values.
            data = {'message': message, 'resource': resource,
                'resourceContactName': resource_contacts, 'user': request.user,
                'user_email': user_email, 'node_url': DJANGO_URL}
            try:
                # Send out email to the resource contacts
                send_mail('Request for information regarding a resource',
                    render_to_string('repository/' \
                      'resource_download_information.email', data),
                    user_email, resource_emails, fail_silently=False)
            except: #SMTPException:
                # If the email could not be sent successfully, tell the user
                # about it.
                messages.error(request,
                  _("There was an error sending out the request email."))
            else:
                messages.success(request, _('You have successfully ' \
                    'sent a message to the resource contact person.'))

            # Redirect the user to the resource page.
            return redirect(resource.get_absolute_url())

    # Otherwise, render a new DownloadContactForm instance
    else:
        form = DownloadContactForm(initial={'userEmail': request.user.email,
                                            'message': default_message})

    dictionary = { 'username': request.user,
      'resource': resource,
      'resourceContactName': resource_contacts,
      'resourceContactEmail': resource_emails,
      'form': form }
    return render_to_response('repository/download_contact_form.html',
                        dictionary, context_instance=RequestContext(request))