def convert_newlines_to_br(apps, schema_editor): Post = apps.get_model('northern_winter_beat', 'Post') for post in Post.objects.all(): post.body_en = linebreaks(post.body_en) post.body_da = linebreaks(post.body_da) post.save()
def render(self, context): try: if self.is_variable: copy = self.copy.resolve(context) else: copy = self.copy if context['user'].is_staff and context['request'].GET.get('edit_copys'): copy_obj = Copy.objects.get(key=copy) return '<a href="/admin/kopy/copy/%d/" style="text-decoration: underline;" target="_blank">Edit: %s</a>' % (copy_obj.id, copy_obj) try: if self.br: return linebreaksbr(Copy.objects.get(key=copy).text) elif self.p: return linebreaks(Copy.objects.get(key=copy).text) elif self.title: return title(Copy.objects.get(key=copy).text) return Copy.objects.get(key=copy).text except ObjectDoesNotExist: if self.default: txt = self.default else: txt = 'Please fill me!!' c = Copy.objects.create(key=copy, text=txt) if self.br: return linebreaksbr(c.text) elif self.p: return linebreaks(c.text) elif self.title: return title(Copy.objects.get(key=copy).text) return c.text except template.VariableDoesNotExist: return ''
def import_artist_works(): for o in old_models.Work.objects.using('old').all(): try: artist = new_models.Artist.objects.get(old_id=o.artist_id) except: error = "ARTIST WORK ERROR:\nold work id: %d, artist_id = %d, work title: %s\n\n" % (o.id, o.artist_id, o.title,) ERRORS.append(error) print "ERROR: " + str(o.artist_id) continue data = { 'artist': artist, 'old_id': o.id, 'title': o.title, 'image': get_asset(o.image, 'old_artist_work_images') if o.image != '' else '', 'category': o.cat, 'code': o.code, 'size_text': o.size, 'material': o.material, 'year': getYear(o.yr), 'theme': linebreaks(o.theme), 'attribution': linebreaks(o.attribution), 'price': o.price, 'published': True if o.publish == 1 else False } w = new_models.ArtistWork(**data) w.save() if o.ex_id and o.ex_id != 0: exhib = new_models.Exhibition.objects.get(old_id=o.ex_id) exhib_work = new_models.ExhibitionWork(exhibition=exhib, work=w) exhib_work.save() #exhib.featured_work.add(w) print str(w.id) + ": " + w.title
def render(self, context): try: if self.is_variable: copy = self.copy.resolve(context) else: copy = self.copy if context['user'].is_staff and context['request'].GET.get( 'edit_copys'): copy_obj = Copy.objects.get(key=copy) return '<a href="/admin/kopy/copy/%d/" style="text-decoration: underline;" target="_blank">Edit: %s</a>' % ( copy_obj.id, copy_obj) try: if self.br: return linebreaksbr(Copy.objects.get(key=copy).text) elif self.p: return linebreaks(Copy.objects.get(key=copy).text) elif self.title: return title(Copy.objects.get(key=copy).text) return Copy.objects.get(key=copy).text except ObjectDoesNotExist: if self.default: txt = self.default else: txt = 'Please fill me!!' c = Copy.objects.create(key=copy, text=txt) if self.br: return linebreaksbr(c.text) elif self.p: return linebreaks(c.text) elif self.title: return title(Copy.objects.get(key=copy).text) return c.text except template.VariableDoesNotExist: return ''
def post(self, request, *args, **kwargs): """ Runs create_site management command """ if not request.user.has_perm('add_site'): raise PermissionDenied sitename = request.POST.get('sitename') hostname = request.POST.get('hostname') stdout, stderr = StringIO(), StringIO() if not (sitename and hostname): stderr.write("You must provide a sitename and hostname") try: management.call_command('create_site', f'--sitename={sitename}', f'--hostname={hostname}', stdout=stdout, stderr=stderr) except Exception as ex: # pylint: disable=broad-except stderr.write(str(ex)) return JsonResponse({ 'success_message': linebreaks(stdout.getvalue()), 'failure_message': linebreaks(stderr.getvalue()), })
def test_guido_in_page(self): #'Guido' appears in the content of the response about = About.objects.get() self.assertContains(self.response, about.name) self.assertContains(self.response, about.surname) self.assertContains(self.response, date(about.birthday, "N j, Y")) self.assertContains(self.response, linebreaks(about.biography)) self.assertContains(self.response, about.email) self.assertContains(self.response, about.jabber) self.assertContains(self.response, about.skype) self.assertContains(self.response, linebreaks(about.contacts))
def test_contact(self): response = self.client.get('') contact = Contacts.objects.get(pk=1) self.assertEqual(response.status_code, 200) self.assertContains(response, contact.name) self.assertContains(response, contact.surname) self.assertContains(response, linebreaks(escape(contact.bio))) self.assertContains(response, date(contact.date_of_birth)) self.assertContains(response, contact.email) self.assertContains(response, contact.skype) self.assertContains(response, contact.jabber) self.assertContains(response, linebreaks(escape(contact.contacts)))
def test_contact(self): response = self.client.get(reverse('contact.views.index')) self.assertEqual(response.status_code, 200) data = Contact.objects.get() self.assertContains(response, data.name) self.assertContains(response, data.last_name) self.assertContains(response, date(data.birth_date)) self.assertContains(response, data.email) self.assertContains(response, data.skype) self.assertContains(response, data.jabber) self.assertContains(response, linebreaks(escape(data.bio))) self.assertContains(response, linebreaks(escape(data.other_contacts)))
def migrate_old_posts(): """ Converts all old posts from a simple page format to one Wagtail accepts """ # id=4 is the specific page ID for the news index page index = Page.objects.get(id=4).specific old_posts = Communication.objects.using('old_data').all().order_by('date') user = get_user_model().objects.get(id=1) for post in old_posts: if post.title: title = post.title else: title = 'Archived item from {date}'.format( date=date(post.date, 'D jS F Y')) slug = slugify('{title} - {rand}'.format( title=title, rand=int(round(time.time() * 1000)))) if len(post.text) > 512: intro = post.text[:512] + '...' else: intro = post.text page = BlogPage( search_description='', seo_title=title, show_in_menus=False, slug=slug, title=title, date=post.date, first_published_at=post.date, intro=linebreaks(intro), ) page.body.stream_data = [ ('paragraph', RichText('<p>{body}</p>'.format(body=linebreaks(post.text)))) ] page.tags.add(COMMS_DICT[post.type]) print('Restoring article from {date}'.format(date=post.date)) index.add_child(instance=page) revision = page.save_revision(user=user, submitted_for_moderation=False) revision.publish() page.save()
def custom_linebreaks(value): """ only do linebreak if it contains serious html code """ serios_html = ["<li", "<br", "<ul", "<ol", "<p", "<div", '<table'] for string in serios_html: if string in value: return value return linebreaks(value)
def event_serializer(events): actual_data = [] raw_data = serializers.serialize('python', events) for event in raw_data: e = event['fields'] # Manually create the dictionary for Event querysets startdate = datetime.datetime.combine(e['date'], e['starttime']) enddate = datetime.datetime.combine(e['date'], e['endtime']) d = dict( title=e['title'], eid=event['pk'], startdate=startdate, enddate=enddate, concat=e['title'].split()[0] + str(e['date']).replace('-', ''), eventimage=e['eventimage'], links=[] ) # Add more data to dict that needs more coding around it d['description'] = defaultfilters.linebreaks(e['description']) d['links'].extend( [x['fields'] for x in serializers.serialize('python', [link for link in EventLink.objects.filter(event__pk=d['eid'])] )] ) actual_data.append(d) return actual_data
def merchants_serializer(merchants): actual_data = [] raw_data = serializers.serialize('python', merchants) for merchant in raw_data: d = {} for field, value in merchant['fields'].items(): if field == 'description': d[field] = defaultfilters.linebreaks(value) else: d[field] = value m = merchant['fields'] maps = "https://www.google.com/maps/embed/v1/place?key=AIzaSyC-qMrBgINIQiRrEcdlz8rT6PJWEB-NvGs&q={}+{}+{}+{}".format( m['street'], m['city'], m['state'], m['zip'] ) d['googMapsUrl'] = '+'.join(maps.split()) d['id'] = merchant['pk'] actual_data.append(d) return actual_data
def _send_email(self, subject, body, comm): """Send the message as an email""" from_addr = self.get_mail_id() cc_addrs = self.get_other_emails() from_email = '%s@%s' % (from_addr, settings.MAILGUN_SERVER_NAME) msg = EmailMultiAlternatives(subject=subject, body=body, from_email=from_email, to=[self.email], bcc=cc_addrs + ['*****@*****.**'], headers={ 'Cc': ','.join(cc_addrs), 'X-Mailgun-Variables': { 'comm_id': comm.pk } }) msg.attach_alternative(linebreaks(escape(body)), 'text/html') # atach all files from the latest communication for file_ in comm.files.all(): msg.attach(file_.name(), file_.ffile.read()) msg.send(fail_silently=False) # update communication comm.set_raw_email(msg.message()) comm.delivered = 'email'
def format_enriched_text(datamanager, content, initial_header_level=None, report_level=None, excluded_link=None, text_format=None): """ Converts RST content to HTML and adds encyclopedia links. *excluded_link* is the ENCYCLOPEDIA article_id in which we currently are, if any. """ assert isinstance(content, str) #print(">>>format_enriched_text", content[:30], "----", excluded_link) # we leave RestructuredRext as the DEFAULT format for game contents text_format = text_format or datamanager.AVAILABLE_TEXT_FORMATS.rst content = content.replace( "[INSTANCE_ID]", datamanager.game_instance_id) # handy to build URLs manually with exception_swallower(): content = _generate_game_file_links(content, datamanager) # BEFORE html with exception_swallower(): content = _generate_game_image_thumbnails(content, datamanager) # BEFORE html if text_format == datamanager.AVAILABLE_TEXT_FORMATS.rst: html = advanced_restructuredtext( content, initial_header_level=initial_header_level, report_level=report_level) else: assert text_format in (None, datamanager.AVAILABLE_TEXT_FORMATS.raw) html = linebreaks(content) # only adds <p> and <br> tags #print(">>>format_enriched_text>>>>>", html) with exception_swallower(): html = _generate_encyclopedia_links(html, datamanager, excluded_link=excluded_link) with exception_swallower(): html = _generate_messaging_links(html, datamanager) with exception_swallower(): html = _generate_site_links(html, datamanager) with exception_swallower( ): #FIXME - make it depend on game language, one day html = french_insecable( html) # handles non-breaking spaces, especially # note that conf-enforced RST roles might be used too (|BR|, |NBSP|)... html = html.replace("[BR]", "<br />") # line breaks, handy for vertical spacing html = html.replace( "[NBSP]", chr(160)) # non-breaking spaces, handy for punctuation mainly return html
def disarm_user_input(html): """ Returns html without posible harm In addition - urlizes text if no links are used - breaks lines if no paragraphs are used """ html = defaultfilters.removetags(html, "script style comment") # remove javascript events and style attributes from tags re_comments = re.compile(r'<!--[\s\S]*?(-->|$)') re_tags = re.compile(r'(<[^>\s]+)([^>]+)(>)') re_attrs = re.compile( r"""\s+(on[^=]+|style)=([^"'\s]+|"[^"]*"|'[^']*')""", ) def remove_js_events(match): return "".join(( match.group(1), re_attrs.sub('', match.group(2)), match.group(3), )) html = re_comments.sub("", html) html = re_tags.sub(remove_js_events, html) if "</a>" not in html: html = defaultfilters.urlizetrunc(html, "30") if "</p>" not in html: html = defaultfilters.linebreaks(html) html = defaultfilters.safe(html) return html
def free_detail(request, free_pk): if request.method == 'GET': freeboard = get_object_or_404(FreeBoard, pk= free_pk) freeboard.view_count+=1 freeboard.content = linebreaks(freeboard.content) freeboard.save() serializer = FreeBoardSerializer(freeboard) return Response(serializer.data) elif request.method == 'PUT': freeboard = get_object_or_404(FreeBoard, pk= free_pk) serializer = FreeBoardCreateSerializer(freeboard, data = request.data) if serializer.is_valid(): serializer.save() return Response({ "message": f"{free_pk}글이 성공적으로 수정되었습니다.", }) elif request.method == 'DELETE': freeboard = get_object_or_404(FreeBoard, pk=free_pk) if request.user == freeboard.user: freeboard.delete() result = f"{free_pk}글이 성공적으로 삭제되었습니다." else: result = '다른사람의 글은 삭제 할 수 없습니다.' return Response({ "message": result, })
def post(request): if request.POST: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) #comment.save() msg = EmailMessage( 'New guestbook comment on nickandashley.org', '<strong>Name:</strong> ' + form.data['name'] + '<br><br><strong>Comment:</strong><br><br>' + form.data['comment'], 'Nick and Ashley <*****@*****.**>', ['*****@*****.**', '*****@*****.**']) msg.content_subtype = "html" #msg.send() return HttpResponse(simplejson.dumps({ 'id': comment.id, 'name': comment.name, 'comment': linebreaks(comment.comment), 'created': 'On ' + date(comment.created, 'M j') + ' at ' + date(comment.created, 'g A') }), mimetype='application/json') return HttpResponse(simplejson.dumps({'success': False}), mimetype='application/json', status=500)
def onsite_widget(request): """Used for subtitle dialog""" context = widget.add_config_based_js_files({}, settings.JS_API, 'unisubs-api.js') config = request.GET.get('config', '{}') # strip any query string parama as that chokes the json string match = re.search(r'(?P<qs>}\?.*)', config) if match: config = config[:match.start() + 1] try: config = json.loads(config) except (ValueError, KeyError): raise Http404 if config.get('task'): task = get_object_or_404(Task, pk=config.get('task')) if task.completed: messages.error(request, _(u'That task has already been completed.')) return HttpResponseRedirect( reverse('teams:team_tasks', kwargs={'slug': task.team.slug})) if not config.get('nullWidget'): video_id = config.get('videoID') if not video_id: raise Http404 video = get_object_or_404(models.Video, video_id=video_id) config['returnURL'] = video.get_absolute_url() if not 'effectiveVideoURL' in config: config['effectiveVideoURL'] = video.get_video_url() tv = video.get_team_video() if tv: team = tv.team config['guidelines'] = dict([ (s.key_name.split('_', 1)[-1], linebreaks(urlize(force_escape(s.data)))) for s in team.settings.guidelines() if s.data.strip() ]) # TODO: Go to the tasks panel once the history stuff is implemented config['team_url'] = reverse('teams:settings_basic', kwargs={'slug': team.slug}) else: config['guidelines'] = {} context['widget_params'] = json.dumps(config) general_settings = {} add_general_settings(request, general_settings) context['general_settings'] = json.dumps(general_settings) response = render_to_response('widget/onsite_widget.html', context, context_instance=RequestContext(request)) response['X-XSS-Protection'] = '0' return response
def review_detail(request, movie_pk, review_pk): if request.method == 'GET': review = get_object_or_404(Review, pk=review_pk) review.view_count += 1 review.content = linebreaks() review.save() serializer = ReviewDetailSerializer(review) return Response(serializer.data) elif request.method == 'PUT': review = get_object_or_404(Review, pk=review_pk) serializer = ReviewCreateSerializer(review, data=request.data) if serializer.is_valid(): serializer.save() return Response({ "message": f"{review_pk}글이 성공적으로 수정되었습니다.", }) elif request.method == 'DELETE': review = get_object_or_404(Review, pk=review_pk) if request.user == review.user: review.delete() result = f"{review_pk}글이 성공적으로 삭제되었습니다." else: result = '다른사람의 글은 삭제 할 수 없습니다.' return Response({ "message": result, })
def ajax_register_bug(request): #from megavideo.api.mantis import Mantis p = {} bug_msg = request.REQUEST.get('bug_msg', 0) bug_url = request.REQUEST.get('bug_url', 0) bug_user = request.REQUEST.get('bug_user', 0) bug_channel = request.channel_name title = u'Registro de bug no manager - %s' % getattr('TV_NAME', 'settings', 'Megavideo') content = u"<b>Registro de bug</b> <br>\n" content += u"<b>URL:</b> %s <br>\n" % bug_url content += u"<b>Usuário:</b> %s <br>\n" % bug_user content += u"<b>Rede:</b> %s <br>\n" % bug_channel content += u"<p> %s </p> <br>\n" % linebreaks(bug_msg) msg = EmailMessage(title, content, str(settings.MEGAVIDEO_CONF['email']), [i[1] for i in settings.ADMINS]) msg.content_subtype = "html" status = msg.send() if status: p['status'] = 0 p['msg'] = 'Problema reportado com sucesso' else: p['status'] = 1 p['msg'] = 'Erro ao reportar o problema' return HttpResponse(json.dumps(p), mimetype='application/json')
def grammar(value, arg): "Removes all | separators, creates line breaks and adds grammar description" separator = '|' subvalue = cut(value, separator) event_type_object = arg grammar_text = event_type_object.text_field.split(separator) grammar_text_len = grammar_text.__len__() # check whether a event type is given # also check whether user requested to not add grammar descriptions if (grammar_text[0] != "None") and (grammar_text[0] != "none") and (arg is not None): x = '' y = 0 for i in subvalue.splitlines(): if y < grammar_text_len: strg = ' ' + '(' + grammar_text[y] + ')' else: strg = '' x += i + strg + ' \r\n' y += 1 subvalue = x value = urlize(subvalue) value = linebreaks(value) return value
def dehydrate(self, bundle): bundle.data['facebook_link'] = bundle.obj.get_link bundle.data['member'] = bundle.obj.feed.persona.owner.name bundle.data['party'] = bundle.obj.feed.persona.owner.current_party.name bundle.data['published_str'] = humanize.naturaltime(bundle.obj.published) bundle.data['content_snippet'] = truncatewords_html(linebreaks(append_separators(urlize(bundle.obj.content))), MAX_LENGTH_FOR_STATUS_CONTENT) if bundle.obj.has_attachment: bundle.data['has_attachment'] = True bundle.data['attachment'] = { 'type': bundle.obj.attachment.type, 'is_photo': bundle.obj.attachment.type == 'photo', 'is_video': bundle.obj.attachment.type == 'video', 'is_youtube_video': bundle.obj.attachment.is_youtube_video, 'is_link': bundle.obj.attachment.type == 'link', 'is_event': bundle.obj.attachment.type == 'event', 'is_music': bundle.obj.attachment.type == 'music', 'is_note': bundle.obj.attachment.type == 'note', 'is_nonetype': not bundle.obj.attachment.type, 'link': bundle.obj.attachment.link, 'picture': bundle.obj.attachment.picture, 'name': bundle.obj.attachment.name, 'caption': bundle.obj.attachment.caption, 'description': bundle.obj.attachment.description, 'source': bundle.obj.attachment.source, 'source_clean': bundle.obj.attachment.source_clean } return bundle
def item_content(self, item): output = item.detail if item.status: output = "{0}\n\nStatus: {1}".format(output, item.status) if item.comment: output = "{0}\n\nComment:\n{1}".format(output, item.comment) return {"type" : "html", }, linebreaks(escape(output))
def pretty_body_text(self): '''pre-process for simpler template logic''' _body = self.body if not self.disable_auto_linebreaks: # allow admin users to provide text # that already contains <p> tags _body = linebreaks(_body) return _body
def comment_text(self, obj): return '<a href="%s">%s</a>' % ( reverse( 'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=(obj.id, ) ), defaultfilters.linebreaks(obj.comment) )
def pretty_body_text(self): '''pre-process for simpler template logic''' _body = self.body if not self.article.disable_auto_linebreaks: # allow admin users to provide text # that already contains <p> tags _body = linebreaks(_body) return _body
def item_content(self, item): output = item.detail if item.status: output = "%s\n\nStatus: %s" % (output, item.status) if item.comment: output = "%s\n\nComment:\n%s" % (output, item.comment) return {"type" : "html", }, linebreaks(escape(output))
def to_native(self, value): # Convert model instance text -> text for reading. text = super(ContentTextField, self).to_native(value) # This is equivalent to the django template filter: '{{ value|urlize|linebreaks }}'. Note: Text from the # database is escaped again here (on read) just as a double check for HTML / JS injection. text = linebreaks(urlize(text, None, True, True)) # This ensure links open in a new window (BB-136). return re.sub(r'<a ', '<a target="_blank" ', text)
def get_dict(self): return { "poster": self.user.username if self.user else _("guest"), "selector": self.selector, "text": linebreaks(escape(self.text)), "created_timestamp": self.created.isoformat(), "created": arrow.get(self.created).humanize(locale=get_language()) }
def link_and_linebreak(text, autoescape=True): if text and len(text) > 0: the_text = conditional_escape(text) return mark_safe( linebreaks( bleach.linkify(the_text, callbacks=[callbacks.target_blank]))) else: return text
def get_help_text(self): help_text = ' ' if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) context = template.RequestContext(self.request) help_text += tmpl.render(context) else: help_text += linebreaks(force_unicode(self.help_text)) return safe(help_text)
def render(self, name, value, attrs=None): if self.rel is not None: key = self.rel.get_related_field().name obj = self.rel.to._default_manager.get(**{key: value}) related_url = '../../../%s/%s/%d/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower(), value) value = "<a href='%s'>%s</a>" % (related_url, escape(obj)) final_attrs = self.build_attrs(attrs, name=name) return mark_safe("<div%s>%s</div>" % (flatatt(final_attrs), linebreaks(value)))
def htmlize_text(self, text): if (self.format == self.MARKDOWN_FORMAT): html = markdown(text) elif (self.format == self.CONVERT_LINE_BREAKS_FORMAT): html = linebreaks(text) else: # No formatting. html = text return html
def get_help_text(self, extra_context=None): text = "" extra_context = extra_context or {} if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) text += tmpl.render(extra_context, self.request) else: text += defaultfilters.linebreaks(force_text(self.help_text)) return defaultfilters.safe(text)
def item_content(self, item): output = item.detail if item.status: output = '%s\n\nStatus: %s' % (output, item.status) if item.comment: output = '%s\n\nComment:\n%s' % (output, item.comment) return { "type": "html", }, linebreaks(escape(output))
def get_help_text(self, extra_context=None): text = "" extra_context = extra_context or {} if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) context = template.RequestContext(self.request, extra_context) text += tmpl.render(context) else: text += linebreaks(force_unicode(self.help_text)) return safe(text)
def to_representation(self, value): # Convert model instance text -> text for reading. text = super(ContentTextField, self).to_representation(value) # This is equivalent to the django template filter: # '{{ value|urlize|linebreaks }}'. Note: Text from the # database is escaped again here (on read) just as a # double check for HTML / JS injection. text = linebreaks(urlize(text, None, True, True)) # This ensure links open in a new window (BB-136). return re.sub(r'<a ', '<a target="_blank" ', text)
def handle_noargs(self, **opts): for article in Article.objects.all(): soup = BeautifulSoup(article.content) if soup.find("p"): continue self.stdout.write("Updating %s... " % article.slug) self.stdout.flush() article.content = linebreaks(article.content) article.save() self.stdout.write("done\n")
def email_contact(self): # Send students the instructor's message for student in self.students.all(): if student.email: message = linebreaks(self.message) email_user(self.instructor.email, student.email, None, self.subject, message)
def get_help_text(self, extra_context=None): """Returns the help text for this step.""" text = "" extra_context = extra_context or {} if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) text += tmpl.render(extra_context, self.request) else: text += linebreaks(force_text(self.help_text)) return safe(text)
def get_team_editor_data(self): if self.team_video: team = self.team_video.team return dict([('teamName', team.name), ('type', team.workflow_type), ('guidelines', dict( [(s.key_name.split('_', 1)[-1], linebreaks(urlize(force_escape(s.data)))) for s in team.settings.guidelines() if s.data.strip()]))]) else: return None
def to_dict(self): return { 'pk': self.pk, 'author': self.author.username, 'created_date': timesince(self.created_date), 'content': linebreaks(escape(self.text)), 'total_likes': self.total_likes(), 'thumbnail': self.author.profile.thumbnail(), 'edited': 'edited' if self.edit == True else '', }
def link_and_linebreak(text): """ Converts URLs in text into clickable links with their target attribute set to `_blank`. It wraps givent tags into <p> tags and converts line breaks(\n) to <br> tags. Args: text: (str) Text having URLs to be converted Returns: (str) Text with URLs convert to links """ if text: escaped_text = conditional_escape(text) return mark_safe(linebreaks(bleach.linkify(escaped_text, callbacks=[callbacks.target_blank])))
def get_help_text(self, extra_context=None): """Returns the help text for this step.""" text = "" extra_context = extra_context or {} if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) # mj / jt - https://review.openstack.org/#/c/476147/ text += tmpl.render(extra_context, self.request) else: text += linebreaks(force_text(self.help_text)) return safe(text)
def post(self, request, *args, **kwargs): """ Runs given management command """ management_command = request.POST.get('management_command') stdout, stderr = StringIO(), StringIO() if management_command not in self.allowed_commands: stderr.write('Unknown command "%s"' % management_command) else: try: management.call_command(management_command, stdout=stdout, stderr=stderr) except Exception as ex: # pylint: disable=broad-except stderr.write(str(ex)) return JsonResponse({ 'success_message': linebreaks(stdout.getvalue()), 'failure_message': linebreaks(stderr.getvalue()), })
def format_content(value, format): if format == 'M': # markdown value = markdown(value, settings.MARKDOWN_EXTENSIONS) elif format == 'R': value = restructuredtext(value) elif format == 'H': value = mark_safe(value) else: value = linebreaks(urlize(escape(value))) return value
def link_and_linebreak(text): """ Converts URLs in text into clickable links with their target attribute set to `_blank`. It wraps givent tags into <p> tags and converts line breaks(\n) to <br> tags. Args: text: (str) Text having URLs to be converted Returns: (str) Text with URLs convert to links """ if text: escaped_text = conditional_escape(text) return mark_safe(linebreaks(bleach.linkify(escaped_text, callbacks=[callbacks.target_blank]))) return None
def get_team_attributes_for_editor(video): team_video = video.get_team_video() if team_video: team = team_video.team return dict([('teamName', team.name), ('guidelines', dict([(s.key_name.split('_', 1)[-1], linebreaks(urlize(force_escape(s.data)))) for s in team.settings.guidelines() if s.data.strip()]))]) else: return None
def dalite_messages(req, teacher): """ View that returns the current dalite messages. Parameters ---------- req : HttpRequest Request teacher : Teacher Teacher instance returned by `teacher_required` (not used) Returns ------- JsonResponse Response with json data { message: Optional[str] Message to show link: Optional[str] Link to go to when clicked } """ messages = [ { "id": message.id, "title": message.message.title, "text": linebreaks(message.message.text), "colour": message.message.type.colour, "removable": message.message.type.removable, "link": message.message.link, "date": date(message.message.start_date) if message.message.start_date else date(message.message.created_on), "authors": [{ "name": author.name, "picture": author.picture.url if author.picture.name else "", } for author in message.message.authors.all()], } for message in UserMessage.objects.filter(user=teacher.user) if (message.message.start_date is None or message.message.start_date <= datetime.now(pytz.utc)) and ( message.message.end_date is None or message.message.end_date >= datetime.now(pytz.utc)) and message.showing ] data = {"messages": messages} return JsonResponse(data)
def prettify(data): "Take a Zobdata and return a pretty reprsentation of it." if data.data_type == 'BooleanField': if data.value: return 'Yes' else: return 'No' if data.data_type == 'FileField': return mark_safe('<a href="%s">%s</a>' % (data.get_absolute_url(), data.value)) if data.data_type == 'TextField': #return urlize(data.value) return linebreaks(urlize(data.value)) return data.value
def render_html(page): if page.text_format == 'text/plain': return mark_safe(linebreaks(escape(page.content))) elif page.text_format == 'text/markdown': return mark_safe(markdown(escape(page.content))) elif page.text_format == 'text/html': return mark_safe(page.content) else: raise Exception('invalid content type')
def format_content(value, format): if format=='M': # markdown value = markdown(value, settings.MARKDOWN_EXTENSIONS) elif format == 'R': value = restructuredtext(value) elif format=='H': value = mark_safe(value) else: value = linebreaks(urlize(escape(value))) return value
def get_dict(self): return { "comment_id": self.pk, "poster": self.user.username if self.user else _("guest"), "selector": self.selector, "text": linebreaks(escape(self.text)), "created_timestamp": self.created.isoformat(), "created": arrow.get(self.created).humanize(locale=get_language()), "has_edit": self.created != self.edited, "edited_timestamp": self.edited.isoformat(), "edited": arrow.get(self.edited).humanize(locale=get_language()), "edits_total": self.edit_log.count() }
def render(self, context): kwargs = self._prepare_args(context, 'map', accept_args = map_args) provider = context.get('_BAMBU_MAPPING_PROVIDER') if not provider: raise template.TemplateSyntaxError("'marker' tag must be placed within a 'map' tag") if self not in context.render_context: count = 1 else: count = context.render_context[self] options = '{%s}' % ', '.join( [ '%s: %s' % v for v in { 'lat': kwargs.get('lat', 'null'), 'lon': kwargs.get('lon', 'null'), 'draggable': kwargs.get('draggable') and 'true' or 'false', 'title': 'title' in kwargs and ("'%s'" % escapejs(kwargs['title'])) or 'null', 'icon': 'icon' in kwargs and ("'%s'" % escapejs(kwargs['icon'])) or 'null', 'content': 'content' in kwargs and ( "'%s'" % escapejs( linebreaks(kwargs['content']) ) ) or 'null' }.items() ] ) portions = [] portions.append( "bambu_mapping.markers['%s'].push((%s(%s)));" % ( provider.container_id, provider.add_marker(), options ) ) if kwargs.get('callback'): portions.append( provider.add_marker_callback( "bambu_mapping.markers['%s'][%d]" % ( provider.container_id, count - 1 ), kwargs['callback'] ) ) count += 1 context.render_context[self] = count return ''.join(portions)