django.utils.html.strip_tags - python examples

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

81 Examples 7

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : simonw
    def index_components(self):
        return {
            'A': self.satle,
            'C': strip_tags(self.body),
            'B': ' '.join(self.tags.values_list('tag', flat=True)),
        }

3 View Complete Implementation : renderers.py
Copyright MIT License
Author : tfroehlich82
    def put_inside_label(self, html):
        content = '{field} {label}'.format(
            field=html,
            label=self.field.label,
        )
        return render_label(
            content=mark_safe(content),
            label_for=self.field.id_for_label,
            label_satle=escape(strip_tags(self.field_help))
        )

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : HelloGitHub-Team
    def save(self, *args, **kwargs):
        self.modified_time = timezone.now()

        # 首先实例化一个 Markdown 类,用于渲染 body 的文本。
        # 由于摘要并不需要生成文章目录,所以去掉了目录拓展。
        md = markdown.Markdown(extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])

        # 先将 Markdown 文本渲染成 HTML 文本
        # strip_tags 去掉 HTML 文本的全部 HTML 标签
        # 从文本摘取前 54 个字符赋给 excerpt
        self.excerpt = strip_tags(md.convert(self.body))[:54]

        super().save(*args, **kwargs)

3 View Complete Implementation : test_html.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_strip_tags_files(self):
        # Test with more lengthy content (also catching performance regressions)
        for filename in ('strip_tags1.html', 'strip_tags2.txt'):
            with self.subTest(filename=filename):
                path = os.path.join(os.path.dirname(__file__), 'files', filename)
                with open(path, 'r') as fp:
                    content = fp.read()
                    start = datetime.now()
                    stripped = strip_tags(content)
                    elapsed = datetime.now() - start
                self.astertEqual(elapsed.seconds, 0)
                self.astertIn("Please try again.", stripped)
                self.astertNotIn('<', stripped)

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @property
    def added_reviews(self):
        return [
            strip_tags(self.fields[field_name].label)
            for field_name in self.changed_data
            if self.cleaned_data[field_name]
        ]

3 View Complete Implementation : test_search_documents_discourse.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def test_created_docameent_content_should_be_stripped_posts_with_extras(self):
        posts_plus_extras = TOPIC_DETAILS['post_stream']['posts'] + EXTRA_TOPIC_POSTS['post_stream']['posts']
        list_of_fields = [
            [
                post['name'],
                post['username'],
                strip_tags(post['cooked'])
            ] for post in posts_plus_extras
        ]

        self.astertEqual(
            self.docameent.search_content,
            TOPIC_DETAILS['satle'] + '\n' +
            '\n'.join(
                itertools.chain(*list_of_fields)
            )
        )

3 View Complete Implementation : admin.py
Copyright GNU General Public License v3.0
Author : tamuhack-org
def build_approval_email(
    application: Application, confirmation_deadline: timezone.datetime
) -> Tuple[str, str, str, None, List[str]]:
    """
    Creates a datatuple of (subject, message, html_message, from_email, [to_email]) indicating that a `User`'s
    application has been approved.
    """
    subject = f"Your {settings.EVENT_NAME} application has been approved!"

    context = {
        "first_name": application.first_name,
        "event_name": settings.EVENT_NAME,
        "confirmation_deadline": confirmation_deadline,
    }
    html_message = render_to_string("application/emails/approved.html", context)
    message = strip_tags(html_message)
    return subject, message, html_message, None, [application.user.email]

3 View Complete Implementation : helpers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
def send_confirmation_email(request, signature):
    pesation = signature.pesation
    url = request.build_absolute_uri("/pesation/{}/confirm/{}".format(pesation.id, signature.confirmation_hash))
    html_message = render_to_string("pesation/confirmation_email.html", {'firstname': signature.first_name, 'url': url})
    message = strip_tags(html_message)
    with get_connection() as connection:
        msg = EmailMultiAlternatives(_("Confirm your signature to our pesation"),
                           message, to=[signature.email], connection=connection,
                           reply_to=[pesation.confirmation_email_reply])
        msg.attach_alternative(html_message, "text/html")
        msg.send(fail_silently=False)

3 View Complete Implementation : alert_serializers.py
Copyright GNU General Public License v3.0
Author : Uninett
    @staticmethod
    def transform_comment_html(_obj, value):
        """Urlize content, but make sure other tags are stripped as we need
        to output this raw"""
        try:
            return urlize(strip_tags(value))
        except TypeError:
            return ''

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def get_meta_description(self):
        if self.teaser_text:
            return strip_tags(self.teaser_text)

        if self.search_description:
            return self.search_description

        return truncatewords(
            strip_tags(self.body.render_as_block()),
            20
        )

3 View Complete Implementation : utils.py
Copyright MIT License
Author : coogger
def send_mail(subject, template_name, context, to):
    html_content = render_to_string(template_name, context)
    text_content = strip_tags(html_content)
    for to in [user.email for user in to if user.userprofile.email_permission]:
        msg = EmailMultiAlternatives(
            subject, text_content, settings.EMAIL_HOST_USER, [to]
        )
        msg.attach_alternative(html_content, "text/html")
        msg.send()

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @property
    def removed_reviews(self):
        return [
            strip_tags(self.fields[field_name].label)
            for field_name in self.changed_data
            if not self.cleaned_data[field_name]
        ]

3 View Complete Implementation : test_search_documents_discourse.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def test_created_docameent_content_should_be_stripped_posts(self):
        list_of_fields = [
            [
                post['name'],
                post['username'],
                strip_tags(post['cooked'])
            ] for post in TOPIC_DETAILS['post_stream']['posts']
        ]

        self.astertEqual(
            self.docameent.search_content,
            TOPIC_DETAILS['satle'] + '\n' +
            '\n'.join(
                itertools.chain(*list_of_fields)
            )
        )

3 View Complete Implementation : models.py
Copyright MIT License
Author : openlegaldata
    def get_text(self):
        # Convert law content as plain text for ES
        text = strip_tags(html.unescape(self.content))

        from oldp.apps.references.models import LawReferenceMarker

        return LawReferenceMarker.remove_markers(text)

3 View Complete Implementation : report_mailing.py
Copyright MIT License
Author : maykinmedia
    def send_email(self, recipients, queryset):
        context = self.get_context(queryset)
        html_content = render_to_string(self.template_name, context)
        text_content = html.unescape(strip_tags(html_content))

        send_mail(
            subject=settings.TIMELINE_DIGEST_EMAIL_SUBJECT,
            message=text_content,
            from_email=settings.TIMELINE_DIGEST_FROM_EMAIL,
            recipient_list=recipients,
            fail_silently=False,
            html_message=html_content
        )
        logger.info('Notification emails sent to: %s', recipients)

3 View Complete Implementation : payment_email.py
Copyright GNU General Public License v3.0
Author : evernote
    def send(self):
        """Sends the payment email along with the invoice."""
        body = self.get_body()

        # Set non-empty body according to
        # http://stackoverflow.com/questions/14580176/confusion-with-sending-email-in-django
        mail = EmailMultiAlternatives(subject=self.get_subject(),
                                      body=strip_tags(body),
                                      to=self.get_recipient_list(),
                                      cc=self.get_cc_list(),
                                      bcc=self.get_bcc_list())
        mail.attach_alternative(body, 'text/html')

        for attachment in self.attachments:
            mail.attach_file(attachment[0], attachment[1])

        return mail.send()

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def get_meta_description(self):
        if self.search_description:
            return self.search_description

        return truncatewords(
            strip_tags(self.body.render_as_block()),
            20
        )

3 View Complete Implementation : admin.py
Copyright GNU General Public License v3.0
Author : tamuhack-org
def build_rejection_email(application: Application) -> Tuple[str, str, None, List[str]]:
    """
    Creates a datatuple of (subject, message, html_message, from_email, [to_email]) indicating that a `User`'s
    application has been rejected.
    """
    subject = f"Regarding your {settings.EVENT_NAME} application"

    context = {"first_name": application.first_name, "event_name": settings.EVENT_NAME}
    html_message = render_to_string("application/emails/rejected.html", context)
    message = strip_tags(html_message)
    return subject, message, html_message, None, [application.user.email]

3 View Complete Implementation : get_job.py
Copyright GNU General Public License v3.0
Author : amfoss
def sendThreadEmail(thread):
    send_mail(
        getSubject(thread, now),
        strip_tags(thread.threadMessage),
        from_email,
        [thread.email],
        html_message=thread.threadMessage,
        fail_silently=False,
    )

3 View Complete Implementation : dashboard.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
@login_required
def new_message(request, id):
    user = request.user
    receiver = User.objects.get(pk=id)
    profile = user.get_profile()
    receiver_profile = receiver.get_profile()
    if request.method == 'POST':
        msg = send_message(request, strip_tags(request.POST['message']), receiver=receiver)
        messages.success(request, _('Your message successfully sent.'))
        return HttpResponseRedirect(reverse('show_message', args=[msg.id]))
    context = {'participant':receiver,
               'toname':receiver_profile.private_name,
               'friends':profile.is_friend(receiver_profile),
    }
    return render_to_response('dashboard/show_message.html', context, context_instance=RequestContext(request))

3 View Complete Implementation : blog_tags.py
Copyright MIT License
Author : liangliangyy
@register.filter(is_safe=True)
@stringfilter
def truncate(content):
    from django.utils.html import strip_tags

    return strip_tags(content)[:150]

3 View Complete Implementation : renderers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : zostera
    def add_checkbox_label(self, html):
        return html + render_label(
            content=self.field.label,
            label_for=self.field.id_for_label,
            label_satle=escape(strip_tags(self.field_help)),
            label_clast="form-check-label",
        )

3 View Complete Implementation : renderers.py
Copyright MIT License
Author : tfroehlich82
    def add_help_attrs(self, widget=None):
        if widget is None:
            widget = self.widget
        if not isinstance(widget, CheckboxInput):
            widget.attrs['satle'] = widget.attrs.get(
                'satle',
                escape(strip_tags(self.field_help))
            )

3 View Complete Implementation : monitor.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unhaggle
    def _prepare_message(self, message):
        # slack don't process html ensaties
        html_parser = HTMLParser.HTMLParser()
        message = html_parser.unescape(message)
        # slack also don't render html itself
        message = strip_tags(message)
        return message

3 View Complete Implementation : utils.py
Copyright GNU Affero General Public License v3.0
Author : edx
def strip_html_tags(text, strip_ensaties=True):
    """
    Return (str): Text without any html tags and ensaties.

    Args:
        text (str): text having html tags
        strip_ensaties (bool): If set to True html ensaties are also stripped
    """
    text = strip_tags(text)
    if strip_ensaties:
        text = re.sub(r'&([a-zA-Z]{4,5}|#[0-9]{2,4});', '', text)
    return text

3 View Complete Implementation : helpers.py
Copyright Apache License 2.0
Author : netbox-community
@register.filter(is_safe=True)
def gfm(value):
    """
    Render text as GitHub-Flavored Markdown
    """
    # Strip HTML tags
    value = strip_tags(value)

    # Render Markdown with GFM extension
    html = markdown(value, extensions=['mdx_gfm'])

    return mark_safe(html)

0 View Complete Implementation : mobile_survey.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def notify_mobile_survey_start(self, request, mobile_survey):
        admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
        email_context = {
            "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
            "link": request.build_absolute_uri(reverse("home")),
            "greeting": _(
                "Welcome to Arches!  You've just been added to a Mobile Survey.  \
                Please take a moment to review the mobile_survey description and mobile_survey start and end dates."
            ),
            "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
        }

        html_content = render_to_string("email/general_notification.htm", email_context)
        text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

        # create the email, and attach the HTML version as well.
        for user in self.get_mobile_survey_users(mobile_survey):
            msg = EmailMultiAlternatives(
                _("You've been invited to an {app_name} Survey!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send()

0 View Complete Implementation : mobile_survey.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def notify_mobile_survey_end(self, request, mobile_survey):
        admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
        email_context = {
            "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
            "link": request.build_absolute_uri(reverse("home")),
            "greeting": _(
                "Hi!  The Mobile Survey you were part of has ended or is temporarily suspended. \
                Please permform a final sync of your local dataset as soon as possible."
            ),
            "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
        }

        html_content = render_to_string("email/general_notification.htm", email_context)
        text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

        # create the email, and attach the HTML version as well.
        for user in self.get_mobile_survey_users(mobile_survey):
            msg = EmailMultiAlternatives(
                _("There's been a change to an {app_name} Survey that you're part of!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send()

0 View Complete Implementation : abstracts.py
Copyright MIT License
Author : bashu
    def get_meta_description(self):
        return strip_tags(self.excerpt) or truncatewords(strip_tags(self.body), 20)

0 View Complete Implementation : files.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def zip_files(files, article_specific=False):
    file_name = '{0}.zip'.format(uuid4())

    # Copy files into a temp dir
    _dir = os.path.join(settings.BASE_DIR, 'files/temp', str(uuid4()))
    os.makedirs(_dir, 0o775)

    for file in files:

        if article_specific and file.article_id:
            folder_name = '{id} - {satle}'.format(id=file.article_id, satle=strip_tags(file.article.satle))
            article_dir = os.path.join(_dir, folder_name)
            if not os.path.exists(article_dir):
                os.makedirs(article_dir, 0o775)
            shutil.copy(file.self_article_path(), article_dir)
        else:
            shutil.copy(file.self_article_path(), _dir)

    zip_path = '{dir}.zip'.format(dir=_dir)

    shutil.make_archive(_dir, 'zip', _dir)
    shutil.rmtree(_dir)
    return zip_path, file_name

0 View Complete Implementation : notify_email.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def send_email(subject, to, html, journal, request, bcc=None, cc=None, attachment=None, replyto=None):

    if journal:
        from_email = setting_handler.get_setting('email', 'from_address', journal).value
        subject_setting = setting_handler.get_email_subject_setting('email_subject', subject, journal)
        subject = "[{0}] {1}".format(journal.code, subject_setting if subject_setting else subject)
        html = "{0}<br />{1}".format(html, journal.name)
    else:
        from_email = request.press.main_contact

    if isinstance(to, str):
        if settings.DUMMY_EMAIL_DOMAIN in to:
            to = []
        else:
            to = [to]
    elif isinstance(to, Iterable):
        to = [email for email in to if not settings.DUMMY_EMAIL_DOMAIN in email]

    if request and request.user and not request.user.is_anonymous():
        reply_to = [request.user.email]
        full_from_string = "{0} <{1}>".format(request.user.full_name(), from_email)
    else:
        reply_to = []
        if request:
            full_from_string = "{0} <{1}>".format(
                    sanitize_from(request.site_type.name),
                    from_email
            )
        else:
            full_from_string = from_email

    if replyto:
        reply_to = replyto

    msg = EmailMultiAlternatives(subject, strip_tags(html), full_from_string, to, bcc=bcc, cc=cc, reply_to=reply_to)
    msg.attach_alternative(html, "text/html")

    if request and request.FILES and request.FILES.getlist('attachment'):
        for file in request.FILES.getlist('attachment'):
            file.open()
            msg.attach(file.name, file.read(), file.content_type)
            file.close()

    return msg.send()

0 View Complete Implementation : defaultfilters.py
Copyright GNU General Public License v2.0
Author : blackye
@register.filter(is_safe=True)
@stringfilter
def striptags(value):
    """Strips all [X]HTML tags."""
    return strip_tags(value)

0 View Complete Implementation : feeds.py
Copyright MIT License
Author : chrisdev
    def item_description(self, item):
        content = strip_tags(getattr(item, self.item_description_field))
        return content

0 View Complete Implementation : mail.py
Copyright Apache License 2.0
Author : chrisjrn
def __send_email__(template_prefix, to, kind, **kwargs):

    current_site = Site.objects.get_current()

    ctx = {
        "current_site": current_site,
        "STATIC_URL": settings.STATIC_URL,
    }
    ctx.update(kwargs.get("context", {}))
    subject_template = os.path.join(template_prefix, "%s/subject.txt" % kind)
    message_template = os.path.join(template_prefix, "%s/message.html" % kind)
    subject = "[%s] %s" % (
        current_site.name,
        render_to_string(subject_template, ctx).strip()
    )

    message_html = render_to_string(message_template, ctx)
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    try:
        bcc_email = settings.ENVELOPE_BCC_LIST
    except AttributeError:
        bcc_email = None

    email = EmailMultiAlternatives(
        subject,
        message_plaintext,
        from_email,
        to,
        bcc=bcc_email,
    )
    email.attach_alternative(message_html, "text/html")
    email.send()

0 View Complete Implementation : api.py
Copyright MIT License
Author : cyanfish
@require_GET
@require_api_token
def league_docameent(request):
    try:
        league_tag = request.GET.get('league', None)
        type_ = request.GET.get('type', None)
        strip_html = request.GET.get('strip_html', None) == 'true'
    except ValueError:
        return HttpResponse('Bad request', status=400)

    if not league_tag or not type_:
        return HttpResponse('Bad request', status=400)

    league_doc = LeagueDocameent.objects.filter(league__tag=league_tag, type=type_).first()
    if league_doc is None:
        return JsonResponse({'name': None, 'content': None, 'error': 'not_found'})

    docameent = league_doc.docameent
    content = docameent.content
    if strip_html:
        content = strip_tags(content)

    return JsonResponse({
        'name': docameent.name,
        'content': content
    })

0 View Complete Implementation : pretalx_hugoschedule.py
Copyright MIT License
Author : djangocon
    def handle(self, *args, **options):

        confirmed_keynotes = []
        confirmed_talks = []
        confirmed_workshops = []

        import dceu2019

        hugo_site_path = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(
                        os.path.dirname(
                            dceu2019.__file__
                        )
                    )
                )
            ),
            "hugo_site",
        )

        talk_details_pages_path = os.path.join(
            hugo_site_path,
            "content",
            "talks",
        )

        for submission in submission_models.Submission.objects.filter(state=submission_models.SubmissionStates.CONFIRMED):

            # Create extra properties
            props, __ = models.TalkExtraProperties.objects.get_or_create(submission=submission)

            props.generate_images()
            self.stdout.write(self.style.SUCCESS("Generated new SOME preview images"))

            if not props.slug:
                props.slug = slugify(submission.satle)[:50]
                props.save()

            slug = props.slug

            speakers = list(submission.speakers.all())
            speaker_names = ", ".join([person.get_display_name() for person in speakers])

            images = {}

            if not props.published:
                self.stdout.write(self.style.WARNING("Skipping unpublished talk"))
                continue

            for speaker in speakers:
                self.stdout.write(self.style.SUCCESS("Adding confirmed speaker {}".format(speaker.get_display_name())))
                if speaker.avatar:
                    im = get_thumbnail(speaker.avatar, '200x200', crop='center', quality=80)
                    images[speaker] = "https://members.2019.djangocon.eu" + im.url
                elif speaker.get_gravatar:
                    images[speaker] = "https://www.gravatar.com/avatar/" + speaker.gravatar_parameter
                else:
                    images[speaker] = None

            submission_json = {
                'satle': submission.satle,
                'abstract': submission.abstract,
                'speakers': speaker_names,
                'speaker_image': images[speakers[0]],
                'slug': slug,
                'speaker_twitter': props.speaker_twitter_handle,
                'keynote': 1 if props.keynote else 0,
                'workshop': 1 if props.workshop else 0,
            }

            if props.keynote:
                confirmed_keynotes.append(submission_json)
            elif props.workshop:
                confirmed_workshops.append(submission_json)
            else:
                confirmed_talks.append(submission_json)

            with timezone.override("Europe/Copenhagen"):
                start_time = timezone.localtime(props.submission.slot.start).strftime("%A %H:%M")
                end_time = timezone.localtime(props.submission.slot.end).strftime("%H:%M")

            # astume that resources are slides
            slides = [r.resource.url if r.resource else "" for r in props.submission.active_resources]

            talk_detail_page_content = TALK_PAGE_HTML.format(
                satle=escape(submission.satle),
                description=escape(strip_tags(markdown(submission.abstract))),
                speaker=speaker_names,
                speaker_image=images[speakers[0]],
                talk_satle=submission.satle,
                talk_date=str(datetime.now()),
                talk_abstract=submission.abstract,
                talk_description=submission.description,
                speaker_twitter=props.speaker_twitter_handle or "",
                employer_attribution=props.employer_attribution or "",
                employer_url=props.employer_url or "",
                keynote='true' if props.keynote else 'false',
                workshop='true' if props.workshop else 'false',
                twitter_card='https://members.2019.djangocon.eu' + props.twitter_card_image.url,
                room=props.submission.slot.room,
                timeslot=start_time + "-" + end_time,
                youtube_id=props.youtube_id or "",
                slides1=slides[0] if slides else "",
                slides2=slides[1] if len(slides) > 1 else "",
            )

            if props.youtube_id:
                props.submission.recording_url = "https://www.youtube.com/watch?v={}".format(props.youtube_id)
                props.submission.recording_source = "YT"
                props.submission.save()

            talk_page_file = os.path.join(
                talk_details_pages_path,
                slug + ".md"
            )
            open(talk_page_file, "w").write(talk_detail_page_content)

        json_path = os.path.join(
            hugo_site_path,
            "data",
            "talks.json"
        )

        json.dump(
            confirmed_talks,
            open(json_path, "w")
        )

        json_path = os.path.join(
            hugo_site_path,
            "data",
            "keynotes.json"
        )

        json.dump(
            confirmed_keynotes,
            open(json_path, "w")
        )

        json_path = os.path.join(
            hugo_site_path,
            "data",
            "workshops.json"
        )

        json.dump(
            confirmed_workshops,
            open(json_path, "w")
        )

0 View Complete Implementation : docstrings.py
Copyright Apache License 2.0
Author : edoburu
def _add_model_fields_as_params(app, obj, lines):
    """Improve the docameentation of a Django model subclast.

    This adds all model fields as parameters to the ``__init__()`` method.

    :type app: sphinx.application.Sphinx
    :type lines: list
    """
    param_offset = len(":param ")
    type_offset = len(":type ")
    predefined_params = [
        line[param_offset : line.find(":", param_offset)]
        for line in lines
        if line.startswith(":param ") and ":" in line[param_offset:]
    ]
    predefined_types = [
        line[type_offset : line.find(":", type_offset)]
        for line in lines
        if line.startswith(":type ") and ":" in line[type_offset:]
    ]

    for field in obj._meta.get_fields():
        try:
            help_text = strip_tags(force_text(field.help_text))
            verbose_name = force_text(field.verbose_name).capitalize()
        except AttributeError:
            # e.g. ManyToOneRel
            continue

        # Add parameter
        if field.name not in predefined_params:
            if help_text:
                if verbose_name:
                    if not verbose_name.strip().endswith("."):
                        verbose_name += "."
                    help_text = verbose_name + " " + help_text
                lines.append(u":param %s: %s" % (field.name, help_text))
            else:
                lines.append(u":param %s: %s" % (field.name, verbose_name))

        # Add type
        if field.name not in predefined_types:
            lines.append(_get_field_type(field))

    if (
        "sphinx.ext.inheritance_diagram" in app.extensions
        and "sphinx.ext.graphviz" in app.extensions
        and not any("inheritance-diagram::" in line for line in lines)
    ):
        lines.append(".. inheritance-diagram::")

0 View Complete Implementation : notifications.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
def _send_deadline_mail(deadline, journal):
    astignment = journal.astignment
    course = astignment.get_active_course(journal.user)
    email_data = {}
    email_data['heading'] = 'Upcoming deadline'
    email_data['main_content'] = '''\
    You have an unfinished deadline coming up for {} in {}.'''.format(course.name, astignment.name)
    email_data['extra_content'] = 'Date: {}'.format(deadline['due_date'])
    email_data['button_url'] = '{}/Home/Course/{}/astignment/{}/Journal/{}?nID={}'\
                               .format(settings.BASELINK, course.id, astignment.id, journal.id, deadline['node'])
    email_data['button_text'] = 'View Deadline'
    email_data['profile_url'] = '{}/Profile'.format(settings.BASELINK)

    html_content = render_to_string('call_to_action.html', {'email_data': email_data})
    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(
        subject='Upcoming deadline in {}'.format(astignment.name),
        body=text_content,
        from_email='[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN),
        headers={'Content-Type': 'text/plain'},
        to=[journal.user.email]
    )

    email.attach_alternative(html_content, 'text/html')
    email.send()

0 View Complete Implementation : email.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
@shared_task
def send_email_verification_link(user_pk):
    """Sends an email verification link to the users email adress."""
    user = User.objects.get(pk=user_pk)

    email_data = {}
    email_data['heading'] = 'Email verification'
    token_generator = PastwordResetTokenGenerator()
    token = token_generator.make_token(user)
    email_data['main_content'] = '''\
    We have received a request for email verification. If it was you who made this request, \
    please click the button below to verify your email address. If you have not made this \
    request please ignore this email.'''
    email_data['extra_content'] = 'Token: {}'.format(token)
    email_data['button_url'] = '{}/EmailVerification/{}/{}'.format(settings.BASELINK, user.username, token)
    email_data['button_text'] = 'Verify Email'
    email_data['profile_url'] = '{}/Profile'.format(settings.BASELINK)

    html_content = render_to_string('call_to_action.html', {'email_data': email_data})
    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(
        subject='eJournal email verification',
        body=text_content,
        from_email='[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN),
        headers={'Content-Type': 'text/plain'},
        to=[user.email]
    )

    email.attach_alternative(html_content, 'text/html')
    email.send()

0 View Complete Implementation : email.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
@shared_task
def send_pastword_recovery_link(user_pk):
    user = User.objects.get(pk=user_pk)

    email_data = {}
    email_data['heading'] = 'Pastword recovery'
    token_generator = PastwordResetTokenGenerator()
    token = token_generator.make_token(user)
    email_data['main_content'] = '''\
    We have received a request for pastword recovery. If it was you who made this request, \
    please click the button below to set a new pastword. If you have not made this \
    request please ignore this email.'''
    email_data['extra_content'] = 'Token: {}'.format(token)
    email_data['button_url'] = '{}/PastwordRecovery/{}/{}'.format(settings.BASELINK, user.username, token)
    email_data['button_text'] = 'Set New Pastword'
    email_data['profile_url'] = '{}/Profile'.format(settings.BASELINK)

    html_content = render_to_string('call_to_action.html', {'email_data': email_data})
    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(
        subject='eJournal pastword recovery',
        body=text_content,
        from_email='[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN),
        headers={'Content-Type': 'text/plain'},
        to=[user.email]
    )

    email.attach_alternative(html_content, 'text/html')
    email.send()

0 View Complete Implementation : email.py
Copyright GNU Affero General Public License v3.0
Author : eJourn-al
@shared_task
def send_email_feedback(user_pk, topic, ftype, feedback, user_agent, url, file_content_type=None):
    """Sends the feedback of an user to the developers."""
    user = User.objects.get(pk=user_pk)

    f_body = 'TYPE: {}\n\n'.format(ftype)
    f_body += 'FEEDBACK BY: {}\n'.format(user.username)
    f_body += 'EMAIL: {}\n'.format(user.email)
    f_body += 'TEACHER: {}\n'.format(user.is_teacher)
    f_body += 'ROLES: {}\n'.format(Role.objects.filter(role__user=user).values('name'))
    f_body += 'USER-AGENT: {}\n'.format(user_agent)
    f_body += 'URL: {}\n\n'.format(url)
    f_body += 'THE FEEDBACK:\n{}'.format(feedback)

    r_email_data = {}
    r_email_data['feedback'] = feedback
    r_email_data['profile_url'] = '{}/Profile'.format(settings.BASELINK)

    r_html_content = render_to_string('feedback.html', {'email_data': r_email_data})
    r_text_content = strip_tags(r_html_content)

    from_email = 'eJournal | Support<' + '[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN) + '>'

    attachments = []
    if user.feedback_file:
        r_email_data['attachments_added'] = True
        attachments.append((user.feedback_file.name, user.feedback_file.read(), file_content_type))

    reply = EmailMultiAlternatives(
        subject='Re: {}'.format(topic),
        body=r_text_content,
        attachments=attachments,
        from_email=from_email,
        headers={'Content-Type': 'text/plain'},
        to=[user.email],
        bcc=['[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN)],
    )

    forward = EmailMultiAlternatives(
        subject='Additional support info: {}'.format(topic),
        body=f_body,
        attachments=attachments,
        from_email=from_email,
        to=['[email protected]{}'.format(settings.EMAIL_SENDER_DOMAIN)],
        headers={'Content-Type': 'text/plain'}
    )

    reply.attach_alternative(r_html_content, 'text/html')
    reply.send()
    forward.send()

    if user.feedback_file:
        user.feedback_file.delete()

0 View Complete Implementation : dashboard.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
@login_required
def show_message(request, id):
    user = request.user
    profile = user.get_profile()
    msg = Message.objects.get(Q(sender=user)|Q(receiver=user), pk=id)
    msg.message_set.filter(read=False, receiver=user).update(read=True)
    if msg.receiver == user:
        participant = msg.sender
        receiver = msg.sender
        if not msg.read:
            msg.read = True
            msg.save()
    else:
        participant = msg.receiver
        receiver = msg.receiver
    participant_profile = participant.get_profile()
    if request.method == 'POST':
        send_message(request, strip_tags(request.POST['message']), receiver=receiver, replyto=msg)
        msg.last_message_time = datetime.now()
        msg.replied = True
        msg.save()
        messages.success(request, _('Your message successfully sent.'))

    msgs = list(Message.objects.select_related().filter(replyto=msg))
    msgs.append(msg)
    msgslist = []
    for m in msgs:
        m.sender_name =  m.sender.get_full_name() if m.sender == user else m.get_sender_name()
        msgslist.append(m)
    context = {'msg':msg,
               'msgs':msgslist,
               'participant':participant,
               'toname':participant.get_profile().private_name,
               'friends':profile.is_friend(participant_profile),
    }
    return render_to_response('dashboard/show_message.html', context, context_instance=RequestContext(request))

0 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def get_meta_description(self):
        return truncatewords(
            strip_tags(self.body.render_as_block()),
            20
        )

0 View Complete Implementation : __init__.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
@transaction.atomic
def index_all_topics():
    client = DiscourseClient(
        settings.DISCOURSE_HOST,
        settings.DISCOURSE_API_KEY
    )

    # Get all topics
    topics = client.all_topics()
    results = []

    for topic in topics:
        topic_details = client.topic(topic['id'])

        search_elements = SearchElements()
        search_elements.append(topic_details['satle'])

        topic_posts = topic_details['post_stream']['posts']
        post_ids = set(topic_details['post_stream']['stream'])
        for post in topic_posts:
            post_ids.remove(post['id'])
            search_elements.append(post['name'])
            search_elements.append(post['username'])
            search_elements.append(strip_tags(post['cooked']))

        if post_ids:
            extra_topic_posts = client.posts_for_topic(topic['id'], list(post_ids))
            remaining_posts = extra_topic_posts['post_stream']['posts']
            for post in remaining_posts:
                search_elements.append(post['name'])
                search_elements.append(post['username'])
                search_elements.append(strip_tags(post['cooked']))

        # Create or update the docameent
        docameent_key = KEY_FORMAT.format(topic['id'])

        url = urljoin(
            urlparse(
                '//' + settings.DISCOURSE_HOST,
                'https' if client._secure else 'http',
            ).geturl(),
            '/'.join(['t', str(topic['id'])]),
        )
        # this is the only part that should be @transaction.atomic.. imo
        result = SearchDocameent.objects.update_or_create(
            {
                'satle': topic_details['satle'],
                'url': url,
                'search_content': search_elements.as_string(),
                'search_vector': search_elements.as_search_vector(),
                'data': {
                    'posts_count': topic['posts_count'],
                    'created_at': topic['created_at'],
                },
                'result_type': 'F',
                'key': docameent_key,
            },
            key=docameent_key
        )
        results.append(result)

    return results

0 View Complete Implementation : get_search_content.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
def get_search_content_by_fields(page, fields, get_child_search_content=False):
    search_elements = SearchElements()
    for field in fields:
        if hasattr(page, field):
            content = getattr(page, field)
            if content is None:
                past
            elif isinstance(content, Page):
                child_page = content
                if hasattr(child_page.specific, 'get_search_content') and get_child_search_content:
                    new_content = child_page.specific.get_search_content()
                else:
                    new_content = child_page.satle
            elif isinstance(content, StreamValue):
                new_content = strip_tags(content.__str__())
            elif isinstance(content, str):
                new_content = strip_tags(content)
            else:
                new_content = content.satle
            search_elements.append(new_content)
        else:
            message = 'You are attempting to search by {} which does not exist on {}'.format(field, type(page))
            raise SearchContentException(message=message)

    return search_elements

0 View Complete Implementation : email.py
Copyright MIT License
Author : abelardopardo
def _send_confirmation_message(
    user,
    action: models.Action,
    nmsgs: int,
) -> None:
    """Send the confirmation message.

    :param user: Destination email
    :param action: Action being considered
    :param nmsgs: Number of messages being sent
    :return:
    """
    # Creating the context for the confirmation email
    now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))
    cfilter = action.get_filter()
    context = {
        'user': user,
        'action': action,
        'num_messages': nmsgs,
        'email_sent_datetime': now,
        'filter_present': cfilter is not None,
        'num_rows': action.workflow.nrows,
        'num_selected': action.get_rows_selected(),
    }

    # Create template and render with context
    try:
        html_content = Template(
            str(getattr(ontask_settings, 'NOTIFICATION_TEMPLATE')),
        ).render(Context(context))
        text_content = strip_tags(html_content)
    except TemplateSyntaxError as exc:
        raise Exception(
            _('Syntax error in notification template ({0})').format(str(exc)),
        )

    # Log the event
    context = {
        'num_messages': nmsgs,
        'email_sent_datetime': str(now),
        'filter_present': cfilter is not None,
        'num_rows': action.workflow.nrows,
        'subject': str(ontask_settings.NOTIFICATION_SUBJECT),
        'body': text_content,
        'from_email': str(ontask_settings.NOTIFICATION_SENDER),
        'to_email': [user.email]}
    action.log(user, models.Log.ACTION_EMAIL_NOTIFY, **context)

    # Send email out
    try:
        send_mail(
            str(ontask_settings.NOTIFICATION_SUBJECT),
            text_content,
            str(ontask_settings.NOTIFICATION_SENDER),
            [user.email],
            html_message=html_content)
    except Exception as exc:
        raise Exception(
            _('Error when sending the notification: {0}').format(str(exc)),
        )

0 View Complete Implementation : schema.py
Copyright GNU General Public License v3.0
Author : amfoss
    def mutate(self, info, formID, name, email=None, phone=None, formData=None):
        form = Form.objects.get(id=formID)
        formHash = form.formHash
        if form.isActive:
            if form.submissionDeadline is None or datetime.now() < form.submissionDeadline:
                regCount = Application.objects.filter(form_id=formID).count()
                if form.applicationLimit is None or regCount < form.applicationLimit or form.onSubmitAfterMax == 'W':
                    status = 'W'
                    if form.applicationLimit is None or regCount < form.applicationLimit:
                        status = 'U'
                    if email is not None or phone is not None:
                        apps = Application.objects.filter((Q(email=email) & Q(phone=phone)) & Q(form_id=formID))
                        apps.count()
                        if form.allowMultiple or apps.count() == 0:
                            str = formHash + phone
                            hashEncoded = hashlib.md5(str.encode())
                            hash = hashEncoded.hexdigest()
                            app = Application.objects.create(
                                name=name,
                                submissionTime=datetime.now(),
                                form_id=formID,
                                email=email,
                                phone=phone,
                                formData=formData,
                                hash=hash,
                                status=status
                            )
                            app.save()
                            temp = Template(form.rsvpMessage)
                            context = Context({'name': name, 'hash': hash})
                            htmlMessage = temp.render(context)
                            send_mail(
                                form.rsvpSubject,
                                strip_tags(htmlMessage),
                                from_email,
                                [email],
                                html_message=htmlMessage,
                                fail_silently=True,
                            )
                            return responseObj(id=app.id, status=status)
                        else:
                            raise APIException('Registered already with the same email or phone number.',
                                               code='ALREADY_REGISTERED')
                    else:
                        raise APIException('Either Name or Phone Number is required.', code='REQUIRED_FIELD_MISSING')
                else:
                    raise APIException('Maximum possible applications already received for this form.',
                                       code='MAX_APPLICATIONS_EXCEDED')
            else:
                raise APIException('Submission deadline has pasted', code='SUBMISSION_DEADLINE_ENDED')
        else:
            raise APIException('Applications are not accepted for this form right now.', code='INACTIVE_FORM')

0 View Complete Implementation : schema.py
Copyright GNU General Public License v3.0
Author : amfoss
    @login_required
    def resolve_sendRSVPEmail(self, info, **kwargs):
        applicationID = kwargs.get('applicationID')
        app = Application.objects.get(id=applicationID)
        form = app.form
        name = app.name
        email = app.email
        phone = app.phone
        formHash = form.formHash
        str = formHash + phone
        hashEncoded = hashlib.md5(str.encode())
        hash = hashEncoded.hexdigest()

        temp = Template(form.rsvpMessage)
        context = Context({'name': name, 'hash': hash})
        htmlMessage = temp.render(context)

        send_mail(
            form.rsvpSubject,
            strip_tags(htmlMessage),
            from_email,
            [email],
            html_message=htmlMessage,
            fail_silently=True,
        )

        return rsvpResponseObj(status="mails send")

0 View Complete Implementation : get_job.py
Copyright GNU General Public License v3.0
Author : amfoss
    def handle(self, *args, **options):

        # get all groups
        groups = Group.objects.all()

        # for each group
        for group in groups:

            # If the group has attendance enabled
            if group.attendanceEnabled:
                # generate new SSID name if refreshing is required
                refreshSSID(group.attendanceModule)

        threads = Thread.objects.filter(isActive=True)
        for thread in threads:
            if thread.generationTime == time:
                sendThreadEmail(thread)
            if thread.logTime == time:
                logStatus(thread)
                if thread.enableGroupNotification:
                    sendTelegramReport(thread)

        mails = Mailer.objects.all()
        for mail in mails:
            if date.today() == mail.generationEmailDate and mail.generationEmailTime == time:
                applications = Application.objects.values().filter(form=mail.form)
                for application in applications:
                    send_mail(
                        mail.subject,
                        strip_tags(mail.threadMessage),
                        from_email,
                        [application['email']],
                        html_message=mail.threadMessage,
                        fail_silently=False,
                    )

0 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def post(self, request):
        showform = True
        confirmation_message = ""
        postdata = request.POST.copy()
        postdata["ts"] = int(time.time())
        form = ArchesUserCreationForm(postdata, enable_captcha=settings.ENABLE_CAPTCHA)

        if form.is_valid():
            AES = AESCipher(settings.SECRET_KEY)
            userinfo = JSONSerializer().serialize(form.cleaned_data)
            encrypted_userinfo = AES.encrypt(userinfo)
            url_encrypted_userinfo = urlencode({"link": encrypted_userinfo})

            admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
            email_context = {
                "button_text": _("Signup for Arches"),
                "link": request.build_absolute_uri(reverse("confirm_signup") + "?" + url_encrypted_userinfo),
                "greeting": _(
                    "Thanks for your interest in Arches. Click on link below \
                    to confirm your email address! Use your email address to login."
                ),
                "closing": _(
                    "This link expires in 24 hours.  If you can't get to it before then, \
                    don't worry, you can always try again with the same email address."
                ),
            }

            html_content = render_to_string("email/general_notification.htm", email_context)  # ...
            text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

            # create the email, and attach the HTML version as well.
            msg = EmailMultiAlternatives(_("Welcome to Arches!"), text_content, admin_email, [form.cleaned_data["email"]])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            confirmation_message = _(
                "An email has been sent to <br><strong>%s</strong><br> with a link to activate your account" % form.cleaned_data["email"]
            )
            showform = False

        return render(
            request,
            "signup.htm",
            {
                "enable_captcha": settings.ENABLE_CAPTCHA,
                "form": form,
                "postdata": postdata,
                "showform": showform,
                "confirmation_message": confirmation_message,
                "validation_help": validation.pastword_validators_help_texts(),
            },
        )