def test_linebreaksbr(self): self.assertEqual(linebreaksbr('line 1\nline 2'), 'line 1<br />line 2') self.assertEqual(linebreaksbr('line 1\rline 2'), 'line 1<br />line 2') self.assertEqual(linebreaksbr('line 1\r\nline 2'), 'line 1<br />line 2')
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field[ 'field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth's # ReadOnlyPasswordHashWidget. if getattr(widget, 'read_only', False): return widget.render(field, value) if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = force_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.html.format_html(), format_html_join(), " "or django.utils.safestring.mark_safe() instead." % attr, RemovedInDjango20Warning ) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field[ 'field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
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 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 render_change_entry_html(self, info): try: autoland_id = int(info['new'][0]) except (ValueError, TypeError): # Something unexpected was recorded as the autoland id in the # changedescription. This either means we have a serious bug or # someone was attempting to change the field themselves (possibly # maliciously). logger.error('A malformed autoland_id was detected: %s' % info['new'][0]) return self._retrieve_error_txt try: ar = AutolandRequest.objects.get(pk=autoland_id) except: logger.error('An unknown autoland_id was detected: %s' % info['new'][0]) return self._retrieve_error_txt if ar.last_known_status == AutolandEventLogEntry.REQUESTED: return self._waiting_txt elif ar.last_known_status == AutolandEventLogEntry.PROBLEM: return linebreaksbr(self._autoland_problem % ar.last_error_msg) elif ar.last_known_status == AutolandEventLogEntry.SERVED: url = self._job_url % ar.repository_revision template = get_template('mozreview/try_result.html') return template.render(Context({'url': url})) else: return linebreaksbr(self._retrieve_error_txt)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field[ 'field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): warnings.warn( "Deprecated allow_tags attribute used on %s. " "Use django.utils.safestring.format_html(), " "format_html_join(), or mark_safe() instead." % attr, RemovedInDjango20Warning ) result_repr = mark_safe(value) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth's # ReadOnlyPasswordHashWidget. if getattr(widget, 'read_only', False): return widget.render(field, value) if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value) else: if hasattr(value, "__html__"): result_repr = value else: result_repr = linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) else: result_repr = display_for_field(value, f, self.empty_value_display) result_repr = linebreaksbr(result_repr) return conditional_escape(result_repr)
def on_comment_save(sender, comment, *args, **kwargs): post = comment.object post.hit_comments() if comment.is_public and comment.user_name != 'TualatriX': subject = _('Your comment at "%s" now has a reply') % comment.object.title from_email = "IMTX <*****@*****.**>" if comment.has_parent() and comment.parent.mail_notify: to_email = "%s <%s>" % (comment.parent.user_name, comment.parent.email) comment_dict = { 'your_content': comment.parent.content.replace('\n', '| '), 'your_content_html': linebreaksbr(comment.parent.content), 'reply_author': comment.user_name, 'reply_content': comment.content.replace('\n', '| '), 'reply_content_html': linebreaksbr(comment.content), 'url': comment.get_url() } text_content = _('''You said: | %(your_content)s %(reply_author)s replied: | %(reply_content)s Visit this link to view detail: %(url)s''' % comment_dict) html_content = _('''You said: <blockquote>%(your_content_html)s</blockquote> <br /> %(reply_author)s replied: <blockquote>%(reply_content_html)s</blockquote> <br /> Visit this link to view detail: <a href="%(url)s">%(url)s</a>''' % comment_dict) else: to_email = "%s <%s>" % (settings.ADMINS[0][0], settings.ADMINS[0][1]) comment_dict = { 'reply_author': comment.user_name, 'reply_content': comment.content.replace('\n', '| '), 'reply_content_html': linebreaksbr(comment.content), 'url': comment.get_url() } text_content = _('''%(reply_author)s replied: | %(reply_content)s Visit this link to view detail: %(url)s''' % comment_dict) html_content = _('''%(reply_author)s replied: <blockquote>%(reply_content_html)s</blockquote> <br /> Visit this link to view detail: <a href="%(url)s">%(url)s</a>''' % comment_dict) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, "text/html") msg.send()
def test_contact(self): response = self.client.get(reverse('index')) contact = Contact.objects.get(pk=1) self.assertEqual(response.status_code, 200) self.assertContains(response, contact.first_name) self.assertContains(response, contact.last_name) self.assertContains(response, contact.birth_date.strftime("%d.%m.%Y")) self.assertContains(response, linebreaksbr(contact.bio)) self.assertContains(response, contact.email) self.assertContains(response, contact.jabber) self.assertContains(response, contact.skype) self.assertContains(response, linebreaksbr(contact.other_contacts))
def test_content(self): # Tests content self.assertEqual(Contact.objects.count(), 1) base = Contact.objects.all()[0] response = self.client.get(reverse('contact_view')) self.assertEqual(response.status_code, 200) self.assertIn(escape(base.name), response.content) self.assertIn(escape(base.surname), response.content) self.assertIn(date(base.birthdate, 'N j, Y'), response.content) self.assertIn(linebreaksbr(escape(base.bio)), response.content) self.assertIn(escape(base.email), response.content) self.assertIn(escape(base.jabber), response.content) self.assertIn(escape(base.skype), response.content) self.assertIn(linebreaksbr(escape(base.contacts)), response.content)
def import_submission_settings(request, reader): row_list = [row for row in reader] row_list.remove(row_list[0]) for row in row_list: journal = journal_models.Journal.objects.get(code=row[0]) setting_handler.save_setting('general', 'copyright_notice', journal, linebreaksbr(row[1])) setting_handler.save_setting('general', 'submission_checklist', journal, linebreaksbr(row[2])) setting_handler.save_setting('general', 'publication_fees', journal, linebreaksbr(row[3])) setting_handler.save_setting('general', 'reviewer_guidelines', journal, linebreaksbr(row[4]))
def get_initial(self): if self.script_instance: structure = self._find_expected_structure() if structure: condition = structure["condition"] last24hrs = (condition.data["v2"].get("constant", True) if condition else True) initial = { "base-last24hrs": (not last24hrs), "base-recipient": structure["send_mail"].data["recipient"].get("constant"), } for language, data in structure["send_mail"].data["template_data"].items(): for data_key, data_value in data.items(): initial["{0}-{1}".format(language, data_key)] = data_value return initial else: # only returns initial data for the default language default_lang = settings.PARLER_DEFAULT_LANGUAGE_CODE return { default_lang+"-subject": _("Low stock of: {{ product }} from {{ supplier }}"), default_lang+"-body": linebreaksbr(_("Hi!\n" "You are receiving this message because the product " "{{ product}} from {{ supplier }} has a low stock.")), }
def save(self, commit=True): instance = super(CreateUpdateEmailTemplateForm, self).save(False) instance.body_html = linebreaksbr(instance.body_html.strip()) if commit: instance.save() return instance
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)) return bundle
def field_value_pairs(object, fields=None): fields = (fields.split(",") if fields else getattr(object, "field_value_pairs", EVERYTHING)) for field in object._meta.get_fields(): if (field.one_to_many or field.one_to_one or field.many_to_many or field.primary_key or field.name in {"_fts"} or field.name not in fields): continue if field.choices: yield (capfirst(field.verbose_name), object._get_FIELD_display(field)) elif isinstance(field, models.TextField): yield ( capfirst(field.verbose_name), linebreaksbr(getattr(object, field.name)), ) else: value = getattr(object, field.name) if isinstance(value, dt.date): value = local_date_format(value) elif isinstance(value, bool): value = _("yes") if value else _("no") yield (capfirst(field.verbose_name), value)
def mutate(_root, info, title, hint=""): sender = info.context.user if not sender.is_accessible: raise ValueError(_("sorry, the genie is now busy")) topic = Topic.objects.get_or_pseudo(unicode_string=title) hint = smart_lower(hint).strip() or None if hint: validate_user_text(hint, exctype=ValueError) if not topic.valid or (topic.exists and (topic.is_banned or topic.has_entries)): raise ValueError(_("we couldn't handle your request. try again later.")) if not topic.exists: topic = Topic.objects.create_topic(title=title) else: previous_wish = topic.wishes.filter(author=sender) deleted, _types = previous_wish.delete() if deleted: return WishTopic(feedback=_("your wish has been deleted")) Wish.objects.create(topic=topic, author=sender, hint=hint) return WishTopic( feedback=_("your wish is now enlisted. if someone starts a discussion, we will let you know."), hint=linebreaksbr(formatted(hint)), )
def update_catalogue(request): if request.method == 'POST': form = UpdateCatalogueForm(request.POST) if form.is_valid(): period = form.cleaned_data['period'] output = StringIO() updated, unknown = CatalogueUpdater(stdout=output).update( period=period) period = 'last %s' % period if period != 'all' else 'everything' if updated: msg = 'Successfully updated %s (checked %s).' % ( ' and '.join( '%s %s' % (len(v), k) for k, v in updated.items()), period) messages.success(request, msg) detail = 'Updated items:\n' + output.getvalue() messages.info(request, linebreaksbr(detail)) else: msg = 'Nothing to update (checked %s).' % period messages.success(request, msg) return HttpResponseRedirect(reverse('home')) else: form = UpdateCatalogueForm() return TemplateResponse(request, 'qsaui/update.html', dict(form=form))
def format_model(model): name_of = lambda x: x.__class__.__name__.lower() display_of = lambda x: render_to_string('common/%s.html' % name_of(x), {name_of(x): x, 'other': model}) d = {} for field, type in model._fields: if isinstance(type,ManyOf): values = getattr(model,field).all() displays = [display_of(value) for value in values] d[field] = format_list(displays) elif isinstance(type,OneOf): value = getattr(model,field) if value: d[field] = display_of(value) else: d[field] = '(empty)' elif isinstance(type,TextField): value = getattr(model,field) d[field] = defaultfilters.linebreaksbr(value) else: value = getattr(model,field) d[field] = str(value) return format_dict(d)
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 preview(request, slug, text=False, template='admin/mail/notice/preview.html'): """View to preview a notice template.""" notice_class = getNoticeClass(slug) if notice_class is None: raise Http404('Notice could not be found') notice = notice_class() if notice.html_template: body_html = notice.get_body_html() else: body_html = "" if notice.text_template: body_txt = linebreaksbr(notice.get_body_txt()) else: body_txt = "" context = { 'body_html': body_html, 'body_txt': body_txt, 'text': text } return render(request, template, context)
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 process_location_reassignment(domain, transitions, uploaded_filename, user_email): try: Processor(domain, transitions).process() except Exception as e: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Failed", body=linebreaksbr( f"The request could not be completed for file {uploaded_filename}. Something went wrong.\n" f"Error raised : {e}.\n" "Please report an issue if needed."), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.content_subtype = "html" email.send() raise e else: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Completed", body= f"The request has been successfully completed for file {uploaded_filename}.", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.send()
def email_other_cases_details(domain, transitions, uploaded_filename, user_email): try: transition_objs = [ Transition(**transition) for transition in transitions ] filestream = OtherCases(domain).dump(transition_objs) except Exception as e: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Other Cases Dump Failed", body=linebreaksbr( f"The request could not be completed for file {uploaded_filename}. Something went wrong.\n" f"Error raised : {e}.\n" "Please report an issue if needed."), to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) email.content_subtype = "html" email.send() raise e else: email = EmailMessage( subject= f"[{settings.SERVER_ENVIRONMENT}] - Location Reassignment Other Cases Dump Completed", body= f"The request has been successfully completed for file {uploaded_filename}. ", to=[user_email], from_email=settings.DEFAULT_FROM_EMAIL) if filestream: email.attach(filename="Other Cases.zip", content=filestream.read()) else: email.body += "There were no cases found. " email.body += f"Please note that the cases are fetched only for " \ f"{', '.join(OtherCases.valid_operations)}." email.send()
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 timeline_latest_events_json(request, start_after): """ Returns a list of events newer than start_after (a event pk) in json format. """ after = datetime.fromtimestamp(float(start_after)) events = Event.objects.filter(date__gt=after) \ .order_by('date') data = map( lambda e: { 'pk': e.pk, 'date': utcunixtimestamp(e.date), 'message': e.get_message_for_display(), 'task': e.get_task_for_display(), 'comment': linebreaksbr(e.comment), }, events) new_start_after = start_after if events.count() > 0: new_start_after = utcunixtimestamp(events[events.count() - 1].date) return HttpResponse( simplejson.dumps({ 'events': data, 'new_start_after': new_start_after, }))
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 get_email_message(self, models, linked_domains, html=True): error_domain_count = self.get_error_domain_count() separator = "\n" message = _(""" Release complete. {} project(s) succeeded. {} The following content was released: {} The following linked project spaces received content: """).format( self.get_success_domain_count(), _("{} project(s) encountered errors.").format(error_domain_count) if error_domain_count else "", separator.join(["- {}".format(m['name']) for m in models])).strip() for linked_domain in sorted(linked_domains): if not self._get_errors(linked_domain, html): message += _("{}- {} updated successfully").format( separator, linked_domain) else: message += _("{}- {} encountered errors:").format( separator, linked_domain) for msg in self._get_errors(linked_domain, html) + self._get_successes( linked_domain, html): message += separator + " - " + msg return linebreaksbr(message) if html else message
def test_linebreaks(self): self.client.login(username='******', password='******') request = self.rf.get('/admin/constance/config/') request.user = self.superuser response = self.options.changelist_view(request, {}) self.assertContains(response, 'LINEBREAK_VALUE') self.assertContains(response, linebreaksbr('eggs\neggs'))
def timeline_previous_events_json(request, earlier_than): """ Returns a list of 25 events older than earlier_than (a event pk) in json format. """ before = datetime.fromtimestamp(float(earlier_than)) events = Event.objects.filter(date__lt=before) \ .order_by('-date')[:25] data = map( lambda e: { 'pk': e.pk, 'date': utcunixtimestamp(e.date), 'message': e.get_message_for_display(), 'task': e.get_task_for_display(), 'comment': linebreaksbr(e.comment), }, events) new_earlier_than = -1 # signal end of data if events.count() > 0: new_earlier_than = utcunixtimestamp(events[events.count() - 1].date) return HttpResponse( simplejson.dumps({ 'events': data, 'new_earlier_than': new_earlier_than, }))
def get_field_contents(self, field, obj): from django.contrib.admin.templatetags.admin_list import _boolean_icon model_admin = self try: f, attr, value = lookup_field(field, obj, self) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = get_empty_value_display(self) else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_text(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: result_repr = linebreaksbr(result_repr) else: if isinstance(f.rel, ManyToManyRel) and value is not None: result_repr = ", ".join(map(six.text_type, value.all())) else: result_repr = display_for_field(value, f, "") return conditional_escape(result_repr)
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 format_model(model): name_of = lambda x: x.__class__.__name__.lower() display_of = lambda x: render_to_string('common/%s.html' % name_of(x), { name_of(x): x, 'other': model }) d = {} for field, type in model._fields: if isinstance(type, ManyOf): values = getattr(model, field).all() displays = [display_of(value) for value in values] d[field] = format_list(displays) elif isinstance(type, OneOf): value = getattr(model, field) if value: d[field] = display_of(value) else: d[field] = '(empty)' elif isinstance(type, TextField): value = getattr(model, field) d[field] = defaultfilters.linebreaksbr(value) else: value = getattr(model, field) d[field] = str(value) return format_dict(d)
def bbcode(value, code_parser=code_parser): """ >>> data = '[code]print "Lorem [b]imsum[b]"[/code]' >>> bbcode(data) u'<pre><code>print "Lorem [b]imsum[b]"</code></pre>' >>> bbcode('[i]Lorem[/i] \\n [s]imsum[/s]') u'<em>Lorem</em> <br /> <strike>imsum</strike>' >>> bbcode('[list] [*] 1\\n [*]2\\n [*] 3\\n[/list]') u'<ul> <li> 1</li> <li>2</li> <li> 3</li></ul>' >>> bbcode('[list=2] [*] a\\n [*]b\\n [*] c\\n[/list]') u'<ol start="2"> <li> a</li> <li>b</li> <li> c</li></ol>' >>> bbcode("[code]print 123\\nprint '<br/>'[/code]") u'<pre><code>print 123\\nprint '<br/>'</code></pre>' >>> bbcode('[quote=test user]Test quote text[/quote]') u'<blockquote><em>test user</em> <br /> Test quote text</blockquote>' >>> bbcode("[quote]Lorem [quote=sl]imsum[/quote] blabla [/quote]") u'<blockquote>Lorem <blockquote><em>sl</em> <br /> imsum</blockquote> blabla </blockquote>' >>> bbcode('[color=red]Lorem[/color]') u'<span style="color:red">Lorem</span>' >>> bbcode('[color=#FAaF12]Lorem[/color]') u'<span style="color:#FAaF12">Lorem</span>' >>> bbcode('[color=#FAaF121]Lorem[/color]') u'[color=#FAaF121]Lorem[/color]' """ value = escape(value) value = linebreaksbr(value) for bbset in BBCODE_RULES_COMPILED: for _ in xrange(bbset['nested'] + 1): value = bbset['pattern'].sub(bbset['repl'], value) return mark_safe(value)
def get_reply_info(request): """ given a message item, gets relevant information needed in order to compose a reply to the corresponding message gets the sender, the message's recipients and its subject and body """ # get data from the request miid = int(request.GET['miid']) if 'miid' in request.GET else 0 # get MessageItem and Message from miid (mi, m, response) = _get_message_item_and_message(request.user, miid) if response: return response # get list of user, group and course recipients recipients = [{ u'name': u' '.join([m.user.first_name, m.user.last_name]), u'id': m.user.pk, u'type': u'u' }] recipients.extend( [{ u'name': u' '.join([tu.user.first_name, tu.user.last_name]), u'id': tu.user.pk, u'type': u'u' } for tu in MessageTargetUser.objects.filter( message=m).order_by('user__id') if tu.user.id != m.user.id and tu.user.id != request.user.id]) recipients.extend([ { u'name': GroupKVStore.objects.get(vle_course_id=tg.vle_course_id, vle_group_id=tg.vle_group_id).name, u'id': delimiter.join([tg.vle_course_id, tg.vle_group_id]), u'type': u'g' } for tg in MessageTargetGroup.objects.filter(message=m).order_by('id') if GroupKVStore.objects.filter(vle_course_id=tg.vle_course_id, vle_group_id=tg.vle_group_id).exists() ]) recipients.extend([{ u'name': CourseKVStore.objects.get(vle_course_id=tc.vle_course_id).name, u'id': tc.vle_course_id, u'type': u'c' } for tc in MessageTargetCourse.objects.filter(message=m).order_by('id') if CourseKVStore.objects.filter( vle_course_id=tc.vle_course_id).exists()]) # return JSON response data = json.dumps({ 'sender': ' '.join([m.user.first_name, m.user.last_name]), 'recipients': recipients, 'subject': m.subject, 'body': linebreaksbr(escape(m.body)) }) return HttpResponse(data, content_type='application/json')
def echo(update: updater, context: CallbackContext): logger.info('Message Received!') #print(str(type(update.effective_message.chat_id)) + ' - ' + str(update.effective_message.chat_id) + ' - ' + str(GROUP_CHAT_ID) + ' - ' + str(update.effective_message.chat_id == GROUP_CHAT_ID)) if update.effective_message.chat_id != AI_GROUP_CHAT_ID: return """Creating AI Object""" #user = get_user_model() text = linebreaksbr(update.effective_message.text) text = text.replace('Question:<br>', '') text = text.replace('Pairing', '<strong>Pairing</strong>') text = text.replace('Call', '<strong>Call</strong>') text = text.replace('Indicator', '<strong>Indicator</strong>') text = text.replace('Question:', '<strong>Question:</strong>') text = text.partition('Tier:')[0] if 'Indicator' not in text: print('Not an Indicator Message received! Ignoring') return newAI = ArtificialIntelligence( text = text, published_date=timezone.now() ) newAI.save() """ Uncomment the following if you want to reply to the received msg""" #update.effective_message.reply_text('Confirmed!') updater.bot.send_message(AI_CONFIRMATION_CHAT_ID, 'Successfully added AI Message: ' + str(newAI.id))
def resolve(self, context): object = self.object if isinstance(self.object, str): object = resolve_modellookup(context, self.object)[0] object = hg.resolve_lazy(object, context) parts = self.fieldname.split(".") # test if the value has a matching get_FIELDNAME_display function try: value = hg.resolve_lookup( object, f"{'.'.join(parts[:-1])}.get_{parts[-1]}_display".lstrip(".") ) except Exception: value = None if value is None: try: value = hg.resolve_lookup(object, self.fieldname) except AttributeError: # e.g. for non-existing OneToOneField related value pass if isinstance(value, datetime.datetime): value = localtime(value) if self.formatter: value = self.formatter(value) value = localize(value, use_l10n=settings.USE_L10N) if isinstance(value, models.Manager): value = ", ".join([str(x) for x in value.all()]) if isinstance(value, str): value = linebreaksbr(value) return value
def format_content(format, content): depend = { 'markdown': 'markdown', } try: if format == 'markdown': import markdown return markdown.markdown(content) elif format == 'txt': return linebreaksbr(content) elif format == 'html': return content elif format == 'textile': try: import textile return textile.textile(content) except ImportError: raise Exception(u"You must install PyTextile to use textile format.") elif format == 'restructuredtext': try: import docutils return restructuredtext(content) except ImportError: raise Exception(u"You must install docutils to use reST format.") except ImportError: raise Exception('You should install "%s" to use %s format.' % (depend.get(format), format))
def show_comments(comments_list, question): out = '<ul class="scomments">' for c in comments_list[question]: out = out + '<li><span>' + c[0] + ' : </span>' + linebreaksbr( c[1]) + '</li>' out = out + '</ul>' return out
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 post(self, request, *args, **kwargs): content_type = get_object_or_404(ContentType, id=int(kwargs["content_type_id"])) object_id = int(kwargs["object_id"]) get_object_or_404(content_type.model_class(), id=object_id) review = get_object_or_None(Review, user=request.user, content_type=content_type, object_id=object_id) if "delete" in request.POST: if not review: return HttpResponseBadRequest(u"Review does not exist.") else: review.delete() return JsonResponse(dict(status="success", message=u"Your comment was deleted.")) if not review: review = Review(content_type=content_type, object_id=object_id, user=request.user) form = ReviewForm(request.POST, instance=review) if form.is_valid(): review = form.save() return JsonResponse( dict( status="success", message=u"Your comment was saved.", text=linebreaksbr(review.text), author=username(review.user), ) ) errors = {} # noinspection PyUnresolvedReferences for field, errors_list in form.errors.items(): errors[field] = errors_list[0] return JsonResponse(dict(status="error", errors=errors))
def print_variables(self, context): """ Print a set of variables """ text = [] for name, expr in self.variables: # Some extended resolving, to handle unknown variables data = '' try: if isinstance(expr.var, Variable): data = expr.var.resolve(context) else: data = expr.resolve(context) # could return TEMPLATE_STRING_IF_INVALID except VariableDoesNotExist as e: # Failed to resolve, display exception inline keys = [] for scope in context: keys += scope.iterkeys() keys = sorted(set(keys)) # Remove duplicates, e.g. csrf_token return ERROR_TYPE_BLOCK.format(style=PRE_ALERT_STYLE, error=escape(u"Variable '{0}' not found! Available context variables are:\n\n{1}".format(expr, u', '.join(keys)))) else: # Regular format textdata = linebreaksbr(pformat_django_context_html(data)) # At top level, prefix class name if it's a longer result if isinstance(data, (bool,int,basestring,float, Promise)): text.append(BASIC_TYPE_BLOCK.format(style=PRE_STYLE, name=name, value=textdata)) else: text.append(OBJECT_TYPE_BLOCK.format(style=PRE_STYLE, name=name, type=data.__class__.__name__, value=textdata)) return u''.join(text)
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 handle(self, account_id, username, **kwargs): self.couch_user = CouchUser.get_by_username(username) self.account_id = account_id if not self.couch_user: raise CommandError("Option: '--username' must be specified") self.now = datetime.utcnow() account = BillingAccount.objects.get(id=account_id) message = '' if kwargs.get('message'): message += kwargs.get('message') + "\n" message += "Report run {}\n".format(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')) attachments = [] for slug in ( EnterpriseReport.DOMAINS, EnterpriseReport.WEB_USERS, EnterpriseReport.MOBILE_USERS, EnterpriseReport.FORM_SUBMISSIONS, ): (attachment, count) = self._write_file(slug) attachments.append(attachment) message += "{}: {}\n".format(slug, count) cc = [] if kwargs.get('cc'): cc = kwargs.get('cc').split(",") send_html_email_async( "Report on enterprise account {}".format(account.name), self.couch_user.username, linebreaksbr(message), cc=cc, text_content=message, file_attachments=attachments, ) print('Emailed {}{}{}'.format(self.couch_user.username, " and " if cc else "", ", ".join(cc)))
def lookup(the_dict, key): # Try to fetch from the dict, and if it's not found return an empty string, with output safe from HTML escaping. the_dict = json.loads(the_dict) if the_dict.get(key, '')[1] == 'upload': url = reverse('proposals:serve_file', kwargs={'filename': os.path.basename(the_dict.get(key, '')[0])}) return '<a href="%s">Download File</a>' % url else: return linebreaksbr(mark_safe(the_dict.get(key, '')[0]))
def display_extra_data(self, obj): if not obj.extra_data: return "" try: return linebreaksbr(json.dumps(json.loads(obj.extra_data), indent=0)) except ValueError: return "error"
def bbcode(value, code_parser=code_parser): value = escape(value) value = linebreaksbr(value) for bbset in BBCODE_RULES_COMPILED: for _ in xrange(bbset['nested'] + 1): value = bbset['pattern'].sub(bbset['repl'], value) return mark_safe(value)