Python django.utils.html.strip_tags() Examples

The following are 30 code examples of django.utils.html.strip_tags(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.html , or try the search function .
Example #1
Source File: recordprops.py    From open-context-py with GNU General Public License v3.0 6 votes vote down vote up
def get_snippet(self, solr_rec):
        """ get a text highlighting snippet """
        if isinstance(self.highlighting, dict):
            if self.uuid is False:
                if 'uuid' in solr_rec:
                    self.uuid = solr_rec['uuid']
            if self.uuid in self.highlighting:
                if 'text' in self.highlighting[self.uuid]:
                    text_list = self.highlighting[self.uuid]['text']
                    self.snippet = ' '.join(text_list)
                    # some processing to remove fagments of HTML markup.
                    self.snippet = self.snippet.replace('<em>', '[[[[mark]]]]')
                    self.snippet = self.snippet.replace('</em>', '[[[[/mark]]]]')
                    try:
                        self.snippet = '<div>' + self.snippet + '</div>'
                        self.snippet = lxml.html.fromstring(self.snippet).text_content()
                        self.snippet = strip_tags(self.snippet)
                    except:
                        self.snippet = strip_tags(self.snippet)
                    self.snippet = self.snippet.replace('[[[[mark]]]]', '<em>')
                    self.snippet = self.snippet.replace('[[[[/mark]]]]', '</em>') 
Example #2
Source File: models.py    From HelloDjango-blog-tutorial with GNU General Public License v3.0 6 votes vote down vote up
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)

    # 自定义 get_absolute_url 方法
    # 记得从 django.urls 中导入 reverse 函数 
Example #3
Source File: mail.py    From conf_site with MIT License 6 votes vote down vote up
def send_email(to, kind, cc=[], **kwargs):

    current_site = Site.objects.get_current()

    ctx = {"current_site": current_site, "STATIC_URL": settings.STATIC_URL}
    ctx.update(kwargs.get("context", {}))
    subject = "[%s] %s" % (
        current_site.name,
        render_to_string(
            "symposion/emails/%s/subject.txt" % kind, ctx
        ).strip(),
    )

    message_html = render_to_string(
        "symposion/emails/%s/message.html" % kind, ctx
    )
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    email = EmailMultiAlternatives(
        subject, message_plaintext, from_email, to, cc=cc
    )
    email.attach_alternative(message_html, "text/html")
    email.send() 
Example #4
Source File: admin.py    From Ouroboros with GNU General Public License v3.0 6 votes vote down vote up
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] 
Example #5
Source File: schema.py    From cms with GNU General Public License v3.0 6 votes vote down vote up
def mutate(self, info, email):
        user = User.objects.get(email=email)
        if user is not None:
            newPassword = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10))
            user.set_password(newPassword)
            user.save()
            context = {
                "password": newPassword,
                "username": user.username
            }
            message = render_to_string('email/password_reset_email.html', context)
            send_mail('Reset Password | amFOSS CMS', strip_tags(message), from_email, [email], fail_silently=False,
                      html_message=message)
            return userStatusObj(status=True)
        else:
            raise APIException('Email is not registered',
                               code='WRONG_EMAIL') 
Example #6
Source File: payment_email.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #7
Source File: smtp.py    From django-sitemessage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
        """Constructs a MIME message from message and dispatch models."""
        # TODO Maybe file attachments handling through `files` message_model context var.

        if subject is None:
            subject = '%s' % _('No Subject')

        if mtype == 'html':
            msg = self.mime_multipart()
            text_part = self.mime_multipart('alternative')
            text_part.attach(self.mime_text(strip_tags(text), _charset='utf-8'))
            text_part.attach(self.mime_text(text, 'html', _charset='utf-8'))
            msg.attach(text_part)

        else:
            msg = self.mime_text(text, _charset='utf-8')

        msg['From'] = self.from_email
        msg['To'] = to
        msg['Subject'] = subject

        if unsubscribe_url:
            msg['List-Unsubscribe'] = '<%s>' % unsubscribe_url

        return msg 
Example #8
Source File: Template Tag for Truncating Characters.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 6 votes vote down vote up
def blog_tags():
	all_blog_entry = Entry.objects.published()[:5]
	all_blog_entry = [ [p.title, p.slug, p.tags, p.body, p.created ] for p in all_blog_entry ]
	out = []
	for item in all_blog_entry:
		title = str(item[0])
		slug = str(item[1])
		tags = item[2].all()
		tmp_tags_slug = ''
		for tag in tags:
			tmp_tags_slug += str(tag.slug)

		def smart_truncate_chars(value, max_length):
			if len(value) > max_length:
				truncd_val = value[:max_length]
				if value[max_length] != ' ':
					truncd_val = truncd_val[:truncd_val.rfind(' ')]
				return truncd_val + '...'
			return value
		body = smart_truncate_chars(str(item[3].encode('utf-8')), 20) #str(item[3])
		created = str(item[4])
		out.append('%s %s %s %s %s' % (title, slug, tmp_tags_slug, strip_tags(body), created))
	
	return ''.join(out) 
Example #9
Source File: api.py    From heltour with MIT License 6 votes vote down vote up
def league_document(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 = LeagueDocument.objects.filter(league__tag=league_tag, type=type_).first()
    if league_doc is None:
        return JsonResponse({'name': None, 'content': None, 'error': 'not_found'})

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

    return JsonResponse({
        'name': document.name,
        'content': content
    }) 
Example #10
Source File: tests.py    From Spirit with MIT License 6 votes vote down vote up
def test_post_render_static_polls(self):
        """
        Should render the static polls
        """
        comment_html = post_render_static_polls(self.comment)
        self.assertTrue('my poll' in comment_html)

        comment_parts = [
            l.strip()
            for l in strip_tags(comment_html).splitlines()
            if l.strip()
        ]
        self.assertEqual(comment_parts, [
            'my poll',
            '#1 choice 1',
            '#2 choice 2',
            'Name: foo, choice selection: from 1 up to 1, mode: default'
        ]) 
Example #11
Source File: mobile_survey.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #12
Source File: html_attributes.py    From wagtailmodelchoosers with MIT License 5 votes vote down vote up
def html_attributes(attrs, exclude=None):
    """
    Convert a mapping of html attributes to a safe string (with boolean support).

    :type attrs: dict
    :param attrs: the html attributes key/values
    :type exclude: str or list or tuple
    :param exclude: a comma separated string or a list of attributes to exclude
    :rtype: str
    :return: a safe string of html attributes
    """

    # Ensure `exclude` is a list of lowercase keys.
    if exclude is None:
        exclude = []
    elif isinstance(exclude, str):
        exclude = exclude.split(',')
    exclude = list(map(lambda e: e.strip().lower(), exclude))

    html_attrs = []
    for key, val in attrs.items():
        if key.lower() in exclude:
            continue

        # Only include boolean values if `True`, and only add the attribute name (no value) as per HTML specs.
        if isinstance(val, bool):
            if val:
                html_attrs.append(strip_tags(key))

        # Other attributes, display normally.
        else:
            html_attrs.append('{key}="{val}"'.format(key=strip_tags(key), val=conditional_escape(val)))

    return mark_safe(' '.join(html_attrs)) 
Example #13
Source File: test_templatetags.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_caret_escaping(self):
        text = '''
               for(var i = 1;i<iterations;i++){
               fg.save();
               }
               '''

        ugc_text = jinja_tags.ugc_text(text, 9001, 0, 0)
        self.assertEqual(strip_tags(ugc_text), text.replace('<', '&lt;')) 
Example #14
Source File: emails.py    From Ouroboros with GNU General Public License v3.0 5 votes vote down vote up
def send_confirmation_email(app: Application) -> None:
    """
    Sends a confirmation email to a user, which contains their QR code as well as additional event information.
    :param app: The user's application
    :type app: Application
    :return: None
    """
    subject = f"{settings.EVENT_NAME} Confirmation!"
    email_template = "application/emails/confirmed.html"
    context = {"first_name": app.first_name, "event_name": settings.EVENT_NAME}
    html_msg = render_to_string(email_template, context)
    msg = html.strip_tags(html_msg)
    email = mail.EmailMultiAlternatives(
        subject, msg, from_email=None, to=[app.user.email]
    )
    email.attach_alternative(html_msg, "text/html")

    qr_content = json.dumps(
        {
            "first_name": app.first_name,
            "last_name": app.last_name,
            "email": app.user.email,
            "university": app.school.name,
        }
    )
    qr_code = pyqrcode.create(qr_content)
    qr_stream = BytesIO()
    qr_code.png(qr_stream, scale=5)
    email.attach("code.png", qr_stream.getvalue(), "text/png")
    email.send() 
Example #15
Source File: test_templatetags.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_group_link_with_space(self):
        text = 'foo #bar'
        ugc_text = jinja_tags.ugc_text(text, 9001, 1, 1)
        self.assertNotEqual(ugc_text, text)
        self.assertEqual(strip_tags(ugc_text), text) 
Example #16
Source File: test_templatetags.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_url_exploit(self):
        text = '''www.schneier.com/essay-337.html?-#i_hacked_canvas'''
        ugc_text = jinja_tags.ugc_text(text, 9001, 1, 1)
        (link,) = self.css_select(ugc_text, 'a')
        self.assertEqual(strip_tags(ugc_text), text)
        self.assertEqual(link.attrib['href'], 'http://' + text) 
Example #17
Source File: views.py    From djangocms-forms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form_valid(self, form, *args, **kwargs):
        handle_uploaded_files(form)
        form.save(request=self.request)
        form_submission.send(
            sender=self.__class__,
            form=form.form_definition,
            cleaned_data=form.cleaned_data)

        if self.request.is_ajax():
            response = {
                'formIsValid': True,
                'redirectUrl': form.redirect_url,
                'message': form.form_definition.post_submit_msg,
            }
            return JsonResponse(response)
        else:
            messages.success(self.request, strip_tags(form.form_definition.post_submit_msg))
            if form.redirect_url:
                return redirect(form.redirect_url)

            redirect_url = form.cleaned_data['referrer']
            if is_safe_url(redirect_url, self.request.get_host()):
                return redirect(redirect_url)

            # If for some reason someone was manipulated referrer parameter to
            # point to unsafe URL then we will redirect to home page
            # It is not good to raise an error because form was already saved
            # and mail notification was sent
            return redirect('/') 
Example #18
Source File: views.py    From pdpdmeetup with MIT License 5 votes vote down vote up
def get_meetups() -> Optional[List[dict]]:
    """ get all the upcomming meetup events """
    results = None  # return None only if the request fails
    try:
        response = requests.get(MEETUP_EVENTS_URL)
        if response.status_code == 200:
            data = response.json()
            data = sorted(data, key=lambda d: d["time"])
            results = []
            for event in data:
                try:
                    venue = ""
                    if event.get("venue"):
                        venue = f"{event['venue']['name']}"
                        if event["venue"].get("address1"):
                            venue = f"{venue}, {event['venue']['address_1']}"
                    event_datetime = timezone.datetime.fromtimestamp(event["time"] / 1000.0, PERTH_TIMEZONE)
                    og_event_name = f"({dateformat.format(event_datetime, 'D d M')}) {event['name']}"
                    results.append(
                        {
                            "event_id": event["id"],
                            "event_name": event["name"],
                            "event_url": event["link"],
                            "og_event_name": og_event_name,
                            "event_address": venue,
                            "event_description": event["description"],
                            "og_event_description": str(strip_tags(event["description"]).encode("ascii", "ignore")),
                            "event_yes_rsvp_count": event["yes_rsvp_count"],
                            "event_datetime": event_datetime,
                        }
                    )
                except KeyError as e:
                    logger.exception(e)

    except requests.exceptions.RequestException as e:
        print(e)  # need to log this somehow
        logger.exception(e)
    return results 
Example #19
Source File: models.py    From simonwillisonblog with Apache License 2.0 5 votes vote down vote up
def index_components(self):
        return {
            'A': self.title,
            'C': strip_tags(self.body),
            'B': ' '.join(self.tags.values_list('tag', flat=True)),
        } 
Example #20
Source File: test_templatetags.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_group_link(self):
        text = '#i_didnt_hacked_canvas'
        ugc_text = jinja_tags.ugc_text(text, 9001, 1, 1)
        self.assertNotEqual(ugc_text, text)
        self.assertEqual(strip_tags(ugc_text), text) 
Example #21
Source File: utils.py    From CLAtoolkit with GNU General Public License v3.0 5 votes vote down vote up
def get_allcontent_byplatform(platform, unit, user = None, start_date=None, end_date=None):
    # Create filters to retrieve xAPI
    filters = xapi_filter()
    filters.course = unit.code
    if start_date is not None:
        filters.since = start_date

    if end_date is not None:
        filters.until = end_date

    if platform != "all":
        filters.platform = platform

    user_id = None
    if user:
        user_id = user.id
    getter = xapi_getter()
    statements = getter.get_xapi_statements(unit.id, user_id, filters)

    content_list = []
    id_list = []
    for row in statements:
        content = strip_tags(row['object']['definition']['name']['en-US'])
        content = content.replace('"','')
        content = re.sub(r'[^\w\s]','',content) #quick fix to remove punctuation
        content_list.append(content)
        # Is id_list used?
        id_list.append(row['id'])

    return content_list, id_list 
Example #22
Source File: models.py    From Ouroboros with GNU General Public License v3.0 5 votes vote down vote up
def send_html_email(self, template_name, context, subject):
        """Send an HTML email to the user."""
        html_msg = render_to_string(template_name, context)
        msg = html.strip_tags(html_msg)
        self.email_user(subject, msg, None, html_message=html_msg) 
Example #23
Source File: admin.py    From Ouroboros with GNU General Public License v3.0 5 votes vote down vote up
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] 
Example #24
Source File: send_daily_member_update.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_new_members(team, new_members):
    if len(new_members) < 1:
        return
    admins = [
        member.user.user
        for member in Member.objects.filter(team=team, role=Member.ADMIN)
        if member.user.user.account.is_email_confirmed
    ]
    if len(admins) < 1:
        return
    context = {"team": team, "members": new_members, "site": Site.objects.get(id=1)}

    email_subject = "New members joined team %s" % strip_tags(team.name)
    email_body_text = render_to_string(
        "get_together/emails/teams/new_team_members.txt", context
    )
    email_body_html = render_to_string(
        "get_together/emails/teams/new_team_members.html", context
    )
    email_recipients = [admin.email for admin in admins]
    email_from = getattr(
        settings, "DEFAULT_FROM_EMAIL", "noreply@gettogether.community"
    )

    success = send_mail(
        from_email=email_from,
        html_message=email_body_html,
        message=email_body_text,
        recipient_list=email_recipients,
        subject=email_subject,
    )

    for admin in admins:
        EmailRecord.objects.create(
            sender=None,
            recipient=admin,
            email=admin.email,
            subject=email_subject,
            body=email_body_text,
            ok=success,
        ) 
Example #25
Source File: __init__.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def unescape_and_strip_html(text):
    return strip_tags(html.unescape(text)).strip() 
Example #26
Source File: result_records.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def add_snippet_content(self, highlight_dict):
        """Add highlighting text for keyword searches """
        record_hl_dict = highlight_dict.get(self.uuid)
        if not record_hl_dict:
            return None
        
        text_list = record_hl_dict.get('text')
        if not text_list:
            return None

        temp_mark_pre = '[[[[mark]]]]'
        temp_mark_post = '[[[[/mark]]]]'
        snippet = ' '.join(text_list)
        snippet = snippet.strip()
        snippet = snippet.replace(
            configs.QUERY_SNIPPET_HIGHLIGHT_TAG_PRE, 
            temp_mark_pre
        )
        snippet = snippet.replace(
            configs.QUERY_SNIPPET_HIGHLIGHT_TAG_POST, 
            temp_mark_post,
        )
        try:
            snippet = '<div>' + snippet + '</div>'
            snippet = lxml.html.fromstring(snippet).text_content()
            snippet = strip_tags(snippet)
        except:
            snippet = strip_tags(snippet)
        
        self.snippet = snippet.replace(
            temp_mark_pre,
            configs.RECORD_SNIPPET_HIGHLIGHT_TAG_PRE, 
        )
        self.snippet = self.snippet.replace(
            temp_mark_post,
            configs.RECORD_SNIPPET_HIGHLIGHT_TAG_POST, 
        ) 
Example #27
Source File: mail.py    From registrasion with Apache License 2.0 5 votes vote down vote up
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() 
Example #28
Source File: models.py    From cmdbac with Apache License 2.0 5 votes vote down vote up
def meta_description(self):
        if self.description:
            return self.description
        else:
            return strip_tags(self.teaser_html) 
Example #29
Source File: conf.py    From permabots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models
    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):

        # Ignore abstract models
        if not hasattr(obj._meta, 'fields'):
            return lines

        # Grab the field list from the meta class
        fields = obj._meta.fields
        
        for field in fields:
            # Decode and strip any html out of the field's help text
            if hasattr(field, 'help_text'):
                help_text = strip_tags(force_unicode(field.help_text))
            else:
                help_text = None

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            if hasattr(field, 'verbose_name'):
                verbose_name = force_unicode(field.verbose_name).capitalize()
            else:
                verbose_name = ""

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines 
Example #30
Source File: models.py    From richie with MIT License 5 votes vote down vote up
def __str__(self):
        return Truncator(strip_tags(self.body)).words(6, truncate="...")