def test_malformed(self): """ #16395 - Check urlize doesn't highlight malformed URIs """ self.assertEqual(urlize('http:///www.google.com'), 'http:///www.google.com') self.assertEqual(urlize('http://.google.com'), 'http://.google.com') self.assertEqual(urlize('http://@foo.com'), 'http://@foo.com')
def test_idn(self): """ #13704 - Check urlize handles IDN correctly """ self.assertEqual(urlize('http://c✶.ws'), '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>') self.assertEqual(urlize('www.c✶.ws'), '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>') self.assertEqual(urlize('c✶.org'), '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>') self.assertEqual(urlize('info@c✶.org'), '<a href="mailto:[email protected]">info@c✶.org</a>')
def test_urlencoded(self): self.assertEqual( urlize('www.mystore.com/30%OffCoupons!'), '<a href="http://www.mystore.com/30%25OffCoupons" rel="nofollow">' 'www.mystore.com/30%OffCoupons</a>!', ) self.assertEqual( urlize('http://en.wikipedia.org/wiki/Caf%C3%A9'), '<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' 'http://en.wikipedia.org/wiki/Caf%C3%A9</a>', )
def test_parenthesis(self): """ #11911 - Check urlize keeps balanced parentheses """ self.assertEqual( urlize('http://en.wikipedia.org/wiki/Django_(web_framework)'), '<a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' 'http://en.wikipedia.org/wiki/Django_(web_framework)</a>', ) self.assertEqual( urlize('(see http://en.wikipedia.org/wiki/Django_(web_framework))'), '(see <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' 'http://en.wikipedia.org/wiki/Django_(web_framework)</a>)', )
def field_value(revision, field): value = getattr(revision, field) if field in ['is_current', 'is_surrogate', 'no_volume', 'display_volume_with_number', 'no_brand', 'page_count_uncertain', 'title_inferred']: return yesno(value, 'Yes,No') elif field in ['publisher', 'indicia_publisher', 'brand']: return absolute_url(value) elif field in ['notes', 'tracking_notes', 'publication_notes', 'characters', 'synopsis', 'reprint_notes']: return linebreaksbr(value) elif field in ['url']: return urlize(value) elif field in ['indicia_pub_not_printed']: return yesno(value, 'Not Printed,Printed') elif field in ['no_editing', 'no_script', 'no_pencils', 'no_inks', 'no_colors', 'no_letters']: return yesno(value, 'X, ') elif field in ['page_count']: if revision.source_name == 'issue' and revision.changeset.storyrevisions.count(): # only calculate total sum for issue not sequences sum_story_pages = format_page_count(sum_page_counts( revision.changeset.storyrevisions.all())) return u'%s (total sum of story page counts: %s' % \ (format_page_count(value), sum_story_pages) return format_page_count(value) return value
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['raw_url'] = bundle.obj.get_raw_url() bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() bundle.data['description_rendered'] = \ linebreaksbr(urlize(bundle.obj.description)) log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append({ 'created': entry.created, 'user': entry.user, 'code': entry.code, 'diff': entry.diff }) bundle.data['log_entries'] = bundle_log_entries if 'omit_code' in bundle.request.GET: del bundle.data['code'] if 'omit_stylized' in bundle.request.GET: del bundle.data['stylized'] return bundle
def dehydrate(self, bundle): bundle.data['embed_url'] = bundle.obj.get_embed_url() bundle.data['raw_url'] = bundle.obj.get_raw_url() bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url() bundle.data['description_rendered'] = \ linebreaksbr(urlize(bundle.obj.description)) bundle.data['views'] = bundle.obj.views bundle.data['favs'] = bundle.obj.favs() if bundle.data['publish_date']: bundle.data['publish_date'] = \ date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A') log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append({ 'created': entry.created, 'user': entry.user, 'code': entry.code, 'diff': entry.diff }) bundle.data['log_entries'] = bundle_log_entries return bundle
def dehydrate(self, bundle): bundle.data["embed_url"] = bundle.obj.get_embed_url() bundle.data["raw_url"] = bundle.obj.get_raw_url() bundle.data["full_absolute_url"] = bundle.obj.get_full_absolute_url() bundle.data["description_rendered"] = linebreaksbr( urlize(bundle.obj.description) ) log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append( { "created": entry.created, "user": entry.user, "code": entry.code, "diff": entry.diff, } ) bundle.data["log_entries"] = bundle_log_entries if "omit_code" in bundle.request.GET: del bundle.data["code"] if "omit_stylized" in bundle.request.GET: del bundle.data["stylized"] return bundle
def dehydrate(self, bundle): bundle.data["embed_url"] = bundle.obj.get_embed_url() bundle.data["raw_url"] = bundle.obj.get_raw_url() bundle.data["tags_list"] = edit_string_for_tags(bundle.obj.tags.all()) bundle.data["full_absolute_url"] = bundle.obj.get_full_absolute_url() bundle.data["description_rendered"] = linebreaksbr( urlize(bundle.obj.description) ) bundle.data["views"] = bundle.obj.views bundle.data["favs"] = bundle.obj.favs() if bundle.data["publish_date"]: bundle.data["publish_date"] = date( bundle.data["publish_date"], "M d, Y \\a\\t h:i A" ) log_entries = bundle.obj.sniptlogentry_set.all() bundle_log_entries = [] for entry in log_entries: bundle_log_entries.append( { "created": entry.created, "user": entry.user, "code": entry.code, "diff": entry.diff, } ) bundle.data["log_entries"] = bundle_log_entries return bundle
def twittilize(tweet, autoescape=None): # If the tweet post is already escaped with HTML entities or # contains a link (since TypePad is now autolinking new posts), # return it as-is. TypePad already escapes <, > and & to HTML # entities. if tweet.find('<a href') != -1 \ or re.search(html_numeric_entity_re, tweet) \ or re.search(html_named_entity_re, tweet): return mark_safe(tweet) if autoescape: tweet = conditional_escape(tweet) # Auto-link URLs (using Django's implementation). tweet = urlize(tweet) # Auto-link Twitter username references. tweet = re.sub( usernames_re, lambda m: '<a href="http://twitter.com/%s">%s</a>' % (m.group(0), m.group(0)), tweet, ) # Auto-link hashtags. tweet = re.sub( hashtags_re, lambda m: ('<a href="http://twitter.com/search?q=%s">%s</a>' % (html_escaped_to_uri_escaped(m.group(0)), m.group(0))), tweet, ) return mark_safe(tweet)
def addTask(request): """Add a task""" d = {} pagename = request.POST["pagename"] page = TaskPage.objects.get(name__iexact=pagename) if "taskid" not in request.POST.keys(): t = Task() t.text = request.POST["taskcontent"] t.page = page t.save() d["message"] = "Successfully added the task" d["text"] = t.text d["taskid"] = t.id d["update"] = 0 else: taskid = int(request.POST["taskid"]) giventask = Task.objects.get(pk=taskid) giventask.text = request.POST["taskcontent"] giventask.save() d["message"] = "Successfully updated the task" d["text"] = urlize(giventask.text) d["taskid"] = giventask.id d["update"] = 1 # return all the tasks d["error"] = "0" json = simplejson.dumps(d) return HttpResponse(json)
def readme(repository): """ Return a rendered version of the readme for the given repository """ if not repository.readme or not repository.readme.strip(): return 'No readme :(' readme = None try: if repository.readme_type == 'markdown': readme = markup.markdown(repository.readme) elif repository.readme_type == 'textile': readme = markup.textile(repository.readme) elif repository.readme_type == 'rest': readme = markup.restructuredtext(repository.readme) except: pass if not readme: readme = '<pre>%s</pre>' % urlize(repository.readme) try: result = mark_safe(clean_html(readme)) except: result = 'Unreadble readme :(' return result
def external_urlize(value, autoescape=None): from django.template.defaultfilters import urlize value = urlize(value, autoescape) value = value.replace("a href", 'a rel="external" href') return safe(value)
def get_field_display_value(self, f_name): field = self.get_field(f_name) try: return getattr(self, 'get_%s_value'%f_name) except: pass f_value = getattr(self.instance, f_name) if f_value is None: return None if callable(f_value): return f_value() if isinstance(f_value, models.Model): if self._meta.auto_urlize and hasattr(f_value, 'get_absolute_url'): return '<a href="%s">%s</a>'%(f_value.get_absolute_url(), f_value) else: return unicode(f_value) if field.choices: return dict(field.choices).get(f_value, None) if isinstance(field, models.TextField): if self._meta.auto_urlize: f_value = urlize(f_value) if self._meta.auto_linebreaks: f_value = linebreaksbr(f_value) return f_value
def build_settings_docs(docs_path, prefix=None): """ Converts names, descriptions and defaults for settings in ``mezzanine.conf.registry`` into RST format for use in docs, optionally filtered by setting names with the given prefix. """ # String to use instead of setting value for dynamic defaults dynamic = "[dynamic]" lines = [".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py"] for name in sorted(registry.keys()): if prefix and not name.startswith(prefix): continue setting = registry[name] settings_name = "``%s``" % name setting_default = setting["default"] if isinstance(setting_default, str): if gethostname() in setting_default or ( setting_default.startswith("/") and os.path.exists(setting_default)): setting_default = dynamic if setting_default != dynamic: setting_default = repr(deep_force_unicode(setting_default)) lines.extend(["", settings_name, "-" * len(settings_name)]) lines.extend(["", urlize(setting["description"] or "").replace( "<a href=\"", "`").replace( "\" rel=\"nofollow\">", " <").replace( "</a>", ">`_")]) if setting["choices"]: choices = ", ".join(["%s: ``%s``" % (str(v), force_text(k)) for k, v in setting["choices"]]) lines.extend(["", "Choices: %s" % choices, ""]) lines.extend(["", "Default: ``%s``" % setting_default]) with open(os.path.join(docs_path, "settings.rst"), "w") as f: f.write("\n".join(lines).replace("u'", "'").replace("yo'", "you'"))
def crosurlize(value, autoescape=None): """URLize strings. This builds on top of the url'ize function from django. In addition, it creates links for cros specific regexs. TODO(pprabhu) This should be merged with the (much more thorough) urlize functionality in the chromium_status AE app. """ words = value.split(' ') for i in xrange(len(words)): is_url = False word = words[i] if (word.startswith('crbug.com/') or word.startswith('crosreview.com/') or word.startswith('b/')): parts = word.split('/') if len(parts) == 2: try: int(parts[1]) is_url = True except ValueError: pass if is_url: # In-place urlize. words[i] = '<a href="http://%s" rel="nofollow">%s</a>' % (word, word) value = safestring.mark_safe(' '.join(words)) return defaultfilters.urlize(value, autoescape)
def test_non_string_input(self): # Filters shouldn't break if passed non-strings self.assertEqual(addslashes(123), '123') self.assertEqual(linenumbers(123), '1. 123') self.assertEqual(lower(123), '123') self.assertEqual(make_list(123), ['1', '2', '3']) self.assertEqual(slugify(123), '123') self.assertEqual(title(123), '123') self.assertEqual(truncatewords(123, 2), '123') self.assertEqual(upper(123), '123') self.assertEqual(urlencode(123), '123') self.assertEqual(urlize(123), '123') self.assertEqual(urlizetrunc(123, 1), '123') self.assertEqual(wordcount(123), 1) self.assertEqual(wordwrap(123, 2), '123') self.assertEqual(ljust('123', 4), '123 ') self.assertEqual(rjust('123', 4), ' 123') self.assertEqual(center('123', 5), ' 123 ') self.assertEqual(center('123', 6), ' 123 ') self.assertEqual(cut(123, '2'), '13') self.assertEqual(escape(123), '123') self.assertEqual(linebreaks_filter(123), '<p>123</p>') self.assertEqual(linebreaksbr(123), '123') self.assertEqual(removetags(123, 'a'), '123') self.assertEqual(striptags(123), '123')
def test_trailing_multiple_punctuation(self): self.assertEqual( urlize('A test http://testing.com/example..'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..' ) self.assertEqual( urlize('A test http://testing.com/example!!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!' ) self.assertEqual( urlize('A test http://testing.com/example!!!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!' ) self.assertEqual( urlize('A test http://testing.com/example.,:;)"!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)"!' )
def plugin_docs_as_html(plugin, channel): tmpl = Template(plugin.user_docs) ctxt = Context({ 'nick': channel.chatbot.nick, 'channel': channel, 'SITE': 'https://botbot.me', }) return markdown.markdown(urlize(tmpl.render(ctxt)))
def test_uppercase(self): """ #18071 - Check urlize accepts uppercased URL schemes """ self.assertEqual( urlize('HTTPS://github.com/'), '<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>', )
def test_trailing_period(self): """ #18644 - Check urlize trims trailing period when followed by parenthesis """ self.assertEqual( urlize('(Go to http://www.example.com/foo.)'), '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)', )
def test_brackets(self): """ #19070 - Check urlize handles brackets properly """ self.assertEqual( urlize('[see www.example.com]'), '[see <a href="http://www.example.com" rel="nofollow">www.example.com</a>]', ) self.assertEqual( urlize('see test[at[example.com'), 'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>', ) self.assertEqual( urlize('[http://168.192.0.1](http://168.192.0.1)'), '[<a href="http://168.192.0.1](http://168.192.0.1)" rel="nofollow">' 'http://168.192.0.1](http://168.192.0.1)</a>', )
def test_quote_commas(self): """ #20364 - Check urlize copes with commas following URLs in quotes """ self.assertEqual( urlize('Email us at "*****@*****.**", or phone us at +xx.yy'), 'Email us at "<a href="mailto:[email protected]">[email protected]</a>", or phone us at +xx.yy', )
def parse_content(self, content): tmpl = template.Template(content) # Mark our content as HTML safe and strip trailing/leading newlines. content = tmpl.render(template.Context({ 'article': self })) # Return the rendered template file's html with the content now inside of it. return urlize(markdown(content, ['codehilite']))
def test_nofollow(self): """ #12183 - Check urlize adds nofollow properly - see #12183 """ self.assertEqual( urlize('[email protected] or www.bar.com'), '<a href="mailto:[email protected]">[email protected]</a> or ' '<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>', )
def save(self, *args, **kwargs): self.body_html = markdown(urlize(self.body.strip())) if self.tweet: try: self.send_tweet() self.tweet = False except: # sometimes, twitter just doesn't work pass super(LiveBlogEntry, self).save()
def test_quoting(self): """ #9655 - Check urlize doesn't overquote already quoted urls. The teststring is the urlquoted version of 'http://hi.baidu.com/重新开始' """ self.assertEqual( urlize('http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'), '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">' 'http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>', )
def test_url_split_chars(self): # Quotes (single and double) and angle brackets shouldn't be considered # part of URLs. self.assertEqual( urlize('www.server.com"abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>"abc', ) self.assertEqual( urlize('www.server.com\'abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>'abc', ) self.assertEqual( urlize('www.server.com<abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a><abc', ) self.assertEqual( urlize('www.server.com>abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>>abc', )
def format_help(self, description): """ Format the setting's description into HTML. """ for bold in ("``", "*"): parts = [] for i, s in enumerate(description.split(bold)): parts.append(s if i % 2 == 0 else "<b>%s</b>" % s) description = "".join(parts) return mark_safe(urlize(description).replace("\n", "<br>"))
def filter_markdown(value, words=None): html = markdown.markdown(value) html = re.sub(r'<(?!\/?a(?=>|\s.*>))\/?.*?>', '', html) html = mark_safe(linebreaksbr(urlize(html))) if words: return truncatewords_html(html, words) return html
def test_ipv6(self): self.assertEqual( urlize('http://[2001:db8:cafe::2]/api/9'), '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>', )
def test_ipv4(self): self.assertEqual( urlize('http://192.168.0.15/api/9'), '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>', )
def test_invalid_email(self): """ #17592 - Check urlize don't crash on invalid email with dot-starting domain """ self.assertEqual(urlize('*****@*****.**'), '*****@*****.**')
def field_value(revision, field): value = getattr(revision, field) if field in [ 'is_surrogate', 'no_volume', 'display_volume_with_number', 'no_brand', 'page_count_uncertain', 'title_inferred', 'no_barcode', 'no_indicia_frequency', 'no_isbn', 'year_began_uncertain', 'year_ended_uncertain', 'on_sale_date_uncertain' ]: return yesno(value, 'Yes,No') elif field in ['is_current']: res_holder_display = '' if revision.previous(): reservation = revision.source.get_ongoing_reservation() if revision.previous().is_current and not value and reservation: res_holder = reservation.indexer res_holder_display = ' (ongoing reservation held by %s %s)' % \ (res_holder.first_name, res_holder.last_name) return yesno(value, 'Yes,No') + res_holder_display elif field in ['publisher', 'indicia_publisher', 'brand', 'series']: return absolute_url(value) elif field in [ 'notes', 'tracking_notes', 'publication_notes', 'characters', 'synopsis', 'reprint_notes' ]: return linebreaksbr(value) elif field in ['url']: return urlize(value) elif field in ['indicia_pub_not_printed']: return yesno(value, 'Not Printed,Printed') elif field in [ 'no_editing', 'no_script', 'no_pencils', 'no_inks', 'no_colors', 'no_letters' ]: return yesno(value, 'X, ') elif field in ['page_count']: if revision.source_name == 'issue' and \ revision.changeset.storyrevisions.count(): # only calculate total sum for issue not sequences total_pages = sum_page_counts(revision.active_stories()) if revision.variant_of: if revision.changeset.issuerevisions.count() > 1: stories = revision.changeset.storyrevisions\ .exclude(issue=revision.issue) else: stories = revision.variant_of.active_stories() if revision.active_stories().count(): # variant has cover sequence, add page counts without cover stories = stories.exclude(sequence_number=0) total_pages += sum_page_counts(stories) else: # variant has no extra cover sequence total_pages = sum_page_counts(stories) sum_story_pages = format_page_count(total_pages) return u'%s (note: total sum of story page counts is %s)' % \ (format_page_count(value), sum_story_pages) return format_page_count(value) elif field == 'isbn': if value: if validated_isbn(value): return u'%s (note: valid ISBN)' % value elif len(value.split(';')) > 1: return u'%s (note: invalid or inequal ISBNs)' % value elif value: return u'%s (note: invalid ISBN)' % value elif field == 'barcode': if value: barcodes = value.split(';') return_val = value + ' (note: ' for barcode in barcodes: return_val = return_val + u'%s; ' % ("valid UPC/EAN" \ if valid_barcode(barcode) \ else "invalid UPC/EAN or non-standard") return return_val[:-2] + ')' elif field == 'leading_article': if value == True: return u'Yes (sorted as: %s)' % remove_leading_article( revision.name) else: return u'No' elif field in [ 'has_barcode', 'has_isbn', 'has_issue_title', 'has_indicia_frequency', 'has_volume' ]: if hasattr(revision, 'changed'): if revision.changed[field] and value == False: kwargs = {field[4:]: ''} if field[4:] == 'issue_title': kwargs = {'title': ''} if revision.series: value_count = revision.series.active_issues()\ .exclude(**kwargs).count() if value_count: return 'No (note: %d issues have a non-empty %s value)' % \ (value_count, field[4:]) return yesno(value, 'Yes,No') elif field == 'after' and not hasattr(revision, 'changed'): # for previous revision (no attr changed) display empty string return '' return value
def filter_func(s): return linebreaksbr(urlize(s, autoescape=True), autoescape=True)
def test_https(self): self.assertEqual( urlize('https://google.com'), '<a href="https://google.com" rel="nofollow">https://google.com</a>', )
def urlize_and_linebreaks(text, autoescape=True): return linebreaksbr(urlize(text, autoescape=autoescape), autoescape=autoescape)
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 'HTTP_REFERER' in request.META: config['returnURL'] = request.META['HTTP_REFERER'] 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) if not 'returnURL' in config: 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 test_non_string_input(self): self.assertEqual(urlize(123), '123')
def test_email(self): self.assertEqual( urlize('*****@*****.**'), '<a href="mailto:[email protected]">[email protected]</a>', )
def transform_comment_html(_obj, value): """Urlize content, but make sure other tags are stripped as we need to output this raw""" return urlize(strip_tags(value))
def test_unicode(self): self.assertEqual( urlize('https://en.wikipedia.org/wiki/Café'), '<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' 'https://en.wikipedia.org/wiki/Café</a>', )
def send(users, label, extra_context=None, display_subject_prefix=False, no_django_message=False): if extra_context is None: extra_context = {} current_language = get_language() formats = ( 'short.txt', 'full.txt', ) # TODO make formats configurable for user in users: if isinstance(user, basestring): user = User(email=user) recipients = [] # get user language for user from language store defined in # NOTIFICATION_LANGUAGE_MODULE setting try: language = get_notification_language(user) except LanguageStoreNotAvailable: language = "ru" # update context with user specific translations context = Context({ "user": user, "current_site": CurrentSite(language=language, user=user), }) context.update(extra_context) try: notification = Notification.objects.get_notification_for_user( label, user) except Notification.DoesNotExist: log.warn( 'Notification named {1} did not find! current language {2}'. format(user, label, language)) notification = None sms_text = None if notification: language = notification.language activate(language) message_subject = Template( notification.email_subject).render(context) message_html = Template(notification.html).render(context) # strip all tags exclude bleach.sanitizer.ALLOWED_TAGS # a tags allowed message_text = mark_safe(bleach.clean(message_html, strip=True)) if notification.duplicate_by_sms and notification.text: sms_text = Template(notification.text).render(context) else: activate(language) # get prerendered format messages try: messages = get_formatted_messages(formats, label, context) except TemplateDoesNotExist: return message_subject = messages['short.txt'] message_text = messages['full.txt'] message_html = linebreaksbr(urlize(messages['full.txt'])) # Strip newlines from subject subject = ''.join( render_to_string( 'notification/email_subject.txt', { 'message': message_subject, 'display_prefix': display_subject_prefix, }, context).splitlines()) profile = getattr(user, 'profile', None) site_version = profile.registered_from if profile else None settings_object = NotificationSettings.objects.get_for_lang(language) if settings_object and not site_version: context["main_content"] = message_html template_object = settings_object.default_notification_template html_body = template_object.render_html(context) else: html_body = None context['message'] = message_text text_body = render_to_string('notification/email_body.txt', context_instance=context) # GCPatch: create a new message using django-messages django_messages_recipients = [] if user.pk: django_messages_recipients.append(user) if user.email: # Email recipients.append(user.email) if not no_django_message and (not notification or notification.send_in_private): for recipient in django_messages_recipients: msg = django_messages.Message(subject=subject, body=text_body, recipient=recipient) msg.save() send_mail(subject, text_body, get_from_email(site_version), recipients, html_message=html_body) # sends sms if notification was found in db if notification: if sms_text and profile.phone_mobile: sms_send(to=profile.phone_mobile, text=sms_text) # reset environment to original language activate(current_language)
if isinstance(f_value, time): return dateformat.time_format(f_value, time_format) if isinstance(f_value, date): return dateformat.format(f_value, date_format) if isinstance(f_value, decimal.Decimal): return moneyformat(f_value, None, app_settings.THOUSANDS_SEPARATOR) if isinstance(f_value, models.Manager): return ', '.join(map(unicode, f_value.all())) if field and isinstance(field, models.TextField): if self._meta.auto_urlize: f_value = urlize(f_value) if self._meta.auto_linebreaks: f_value = linebreaksbr(f_value) return f_value def get_linkable_field_value(self, instance, f_name, f_value, force=False): url = '' if isinstance(instance, models.Model) and hasattr( instance, 'get_absolute_url'): url = instance.get_absolute_url() elif type(instance) == types.DictType and instance.has_key( 'get_absolute_url'): url = instance['get_absolute_url'] if hasattr(instance, 'get_absolute_url') and (
from django.db import models from django.contrib.auth.models import User from apps.story.models import Story from django.template.defaultfilters import linebreaks, urlize # Create your models here. class CommentManager(models.Manager): def published(self): return self.get_queryset().filter(status=Comment.PUBLISHED) COMMENT_RENDERER = lambda b: linebreaks(urlize(b)) class Comment(models.Model): PUBLISHED = 1 DELETED_BY_OWNER = 2 DELETED_BY_STORY_OWNER = 3 DELETED_BY_ADMINS = 4 STATUS_CHOICES = ((PUBLISHED, 'Published'), (DELETED_BY_OWNER, 'Deleted by owner'), (DELETED_BY_STORY_OWNER, 'Deleted by story owner'), (DELETED_BY_ADMINS, 'Deleted by admins')) story = models.ForeignKey(Story) body = models.TextField() as_html = models.TextField(blank=True) owner = models.ForeignKey(User) posted_at = models.DateTimeField(auto_now_add=True)
def test_word_with_dot(self): self.assertEqual(urlize('some.organization'), 'some.organization'),