def _attachListFields(self, item): """Attaches property instances for list fields to given data entry. This is used in Admin class view methods. """ item.listProperties = copy.deepcopy(self._listProperties[:]) for prop in item.listProperties: try: prop.value = getattr(item, prop.name) if prop.typeName == 'BlobProperty': prop.meta = utils.getBlobProperties(item, prop.name) if prop.value: prop.value = True # release the memory if prop.typeName == 'ManyToManyProperty': # Show pretty list of referenced items. # Show 'None' in place of missing items new_value_list = [] for key in prop.value: new_value_list.append(smart_unicode(db.get(key))) prop.value = ', '.join(new_value_list) except datastore_errors.Error, exc: # Error is raised if referenced property is deleted # Catch the exception and set value to none logging.warning('Error catched in ModelAdmin._attachListFields: %s' % exc) prop.value = None # convert the value to unicode for displaying in list view if hasattr(prop.value, '__call__'): # support for methods prop.value = prop.value() prop.value = smart_unicode(prop.value)
def smart_unicode_cmp(a, b): """Compare two values, converting both to Unicode via smart_unicode() if either value is a string.""" if type(a) in (str, unicode) or type(b) in (str, unicode): a = smart_unicode(a) b = smart_unicode(b) return cmp(a, b)
def _attachListFields(self, item): """Attaches property instances for list fields to given data entry. This is used in Admin class view methods. """ item.listProperties = copy.deepcopy(self._listProperties[:]) for prop in item.listProperties: try: prop.value = getattr(item, prop.name) if prop.typeName == "BlobProperty": prop.meta = utils.getBlobProperties(item, prop.name) if prop.value: prop.value = True # release the memory if prop.typeName == "ManyToManyProperty": # Show pretty list of referenced items. # Show 'None' in place of missing items new_value_list = [] for key in prop.value: new_value_list.append(smart_unicode(db.get(key))) prop.value = ", ".join(new_value_list) except datastore_errors.Error, exc: # Error is raised if referenced property is deleted # Catch the exception and set value to none logging.warning("Error catched in ModelAdmin._attachListFields: %s" % exc) prop.value = None # convert the value to unicode for displaying in list view if hasattr(prop.value, "__call__"): # support for methods prop.value = prop.value() prop.value = smart_unicode(prop.value)
def get_diff(self, context=3): """Compute a diff between old and new values, and return a sequence of dictionaries with 'text' and 'style' keys. """ a = smart_unicode(self.old_value or '').split("\n") b = smart_unicode(self.new_value or '').split("\n") chunks = [] for group in difflib.SequenceMatcher(None, a, b).get_grouped_opcodes(context): chunk = [] chunks.append(chunk) for tag, i1, i2, j1, j2 in group: if tag == 'equal': self._append_diff_lines(chunk, ' ', 'same', a[i1:i2]) if tag == 'replace' or tag == 'delete': self._append_diff_lines(chunk, '- ', 'removed', a[i1:i2]) if tag == 'replace' or tag == 'insert': self._append_diff_lines(chunk, '+ ', 'added', b[j1:j2]) return chunks
def clean(self, value): super(USPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(u'Phone numbers must be in XXX-XXX-XXXX format.')
def clean(self, value): super(USPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u"" value = re.sub("(\(|\)|\s+)", "", smart_unicode(value)) m = phone_digits_re.search(value) if m: return u"%s-%s-%s" % (m.group(1), m.group(2), m.group(3)) raise ValidationError(u"Phone numbers must be in XXX-XXX-XXXX format.")
def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) self.mce_settings['elements'] = "id_%s" % name mce_json = JSONEncoder().encode(self.mce_settings) return mark_safe(u'<textarea%s>%s</textarea> <script type="text/javascript">\tinyMCE.init(%s)</script>' % (flatatt(final_attrs), escape(value), mce_json))
def clean(self, value): """Validate a phone number. """ super(CAPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) raise ValidationError(self.error_messages['invalid'])
def render(self, name, value, attrs=None, choices=()): from django.utils.html import escape from django.newforms.util import flatatt, smart_unicode if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) output = [u'<select%s>' % flatatt(final_attrs)] str_value = smart_unicode(value) for group_label, group in self.choices: if group_label: # should belong to an optgroup group_label = smart_unicode(group_label) output.append(u'<optgroup label="%s">' % escape(group_label)) for k, v in group: option_value = smart_unicode(k) option_label = smart_unicode(v) selected_html = (option_value == str_value) and u' selected="selected"' or '' output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label))) if group_label: output.append(u'</optgroup>') output.append(u'</select>') return u'\n'.join(output)
def changes(request, asset_type=None, asset_id=None, current_user=True, page_number=0, num_per_page=10): """Return a paginated list of recent asset changes, filtered in the following ways: - If 'asset_type' and 'asset_id' are supplied, this limits the changes to those from a single asset. - If 'current_user' is set, this only shows changes to objects that are owned by the currently logged-in user. This returns a JSON result which is used by client-side pagination code. """ changes = models.AssetChangeset.objects.all() if asset_id is not None: changes = changes.filter( content_type=ContentType.objects.get_for_model( get_asset_by_type(asset_type)), object_id=int(asset_id), ) if current_user: changes = changes.extra( tables=["accounts_userasset"], where=[ "accounts_userasset.content_type_id = accounts_assetchangeset.content_type_id", "accounts_userasset.object_id = accounts_assetchangeset.object_id", "accounts_userasset.user_id = %d" % request.user.id ], ) paginator = ObjectPaginator(changes.order_by('-id'), num_per_page=num_per_page, orphans=num_per_page / 2) return { 'remaining': paginator.hits - paginator.last_on_page(page_number), 'html': smart_unicode( loader.render_to_string( 'accounts/asset_changes.html', RequestContext( request, { 'changesets': paginator.get_page(page_number), 'show_asset_name': asset_id is None, }))), }
def clean(self, value): """ Validate a phone number. Strips parentheses, whitespace and hyphens. """ super(AUPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return u'%s' % phone_match.group(1) raise ValidationError(self.error_messages['invalid'])
def html_entities(value, include_essential=False): """ Transforms non ASCII caracters into HTML entities """ ret = '' for char in smart_unicode(value): char_ord = ord(char) if char_ord in htmlentitydefs.codepoint2name and (include_essential or char not in ('<', '>','"',"'", '&')): ret += '&' + htmlentitydefs.codepoint2name[char_ord] + ';' else: ret = ret + char return ret
def get_diff(self, context=3): """Compute a diff between old and new values, and return a sequence of dictionaries with 'text' and 'style' keys. """ a = smart_unicode(self.old_value or '').split("\n") b = smart_unicode(self.new_value or '').split("\n") chunks = [] for group in difflib.SequenceMatcher(None,a,b).get_grouped_opcodes(context): chunk = [] chunks.append(chunk) for tag, i1, i2, j1, j2 in group: if tag == 'equal': self._append_diff_lines(chunk, ' ', 'same', a[i1:i2]) if tag == 'replace' or tag == 'delete': self._append_diff_lines(chunk, '- ', 'removed', a[i1:i2]) if tag == 'replace' or tag == 'insert': self._append_diff_lines(chunk, '+ ', 'added', b[j1:j2]) return chunks
def render(self, name, value=None, attrs=None): final_attrs = self.build_attrs(attrs, name=name) if value: value = smart_unicode(value) final_attrs['value'] = escape(value) if not self.attrs.has_key('id'): final_attrs['id'] = 'id_%s' % name return (u'''<input type="text"%(attrs)s /><div class="autocomplete" id="box_%(name)s"></div> <script type="text/javascript">new Ajax.Autocompleter('%(id)s', 'box_%(name)s', '%(url)s', %(options)s);</script>''' ) % { 'attrs': flatatt(final_attrs), 'name': name, 'id': final_attrs['id'], 'url': self.url, 'options': plist_from_dict(self.options) }
def changes(request, asset_type=None, asset_id=None, current_user=True, page_number=0, num_per_page=10): """Return a paginated list of recent asset changes, filtered in the following ways: - If 'asset_type' and 'asset_id' are supplied, this limits the changes to those from a single asset. - If 'current_user' is set, this only shows changes to objects that are owned by the currently logged-in user. This returns a JSON result which is used by client-side pagination code. """ changes = models.AssetChangeset.objects.all() if asset_id is not None: changes = changes.filter( content_type = ContentType.objects.get_for_model(get_asset_by_type(asset_type)), object_id = int(asset_id), ) if current_user: changes = changes.extra( tables = ["accounts_userasset"], where = ["accounts_userasset.content_type_id = accounts_assetchangeset.content_type_id", "accounts_userasset.object_id = accounts_assetchangeset.object_id", "accounts_userasset.user_id = %d" % request.user.id], ) paginator = ObjectPaginator(changes.order_by('-id'), num_per_page = num_per_page, orphans = num_per_page / 2) return { 'remaining': paginator.hits - paginator.last_on_page(page_number), 'html': smart_unicode(loader.render_to_string( 'accounts/asset_changes.html', RequestContext(request, { 'changesets': paginator.get_page(page_number), 'show_asset_name': asset_id is None, }))), }
def render(self, name, value, attrs=None): if not value: value = "" value = smart_unicode(value) values = simplejson.dumps(self.values,ensure_ascii=False) if not self.tokens: tokens = "" if self.tokens: tokens = ", tokens: '%s'" % self.tokens if not self.minChars: minChars = "" if self.minChars: minChars = ", minChars: '%s'" % self.minChars s = u'' return u"""<input id="id_%s" name="%s" value="%s" type="text" autocomplete="off" %s> <div id="id_%supdate" class=autocomplete style="display:none;border:1px solid black;background-color:white;height:150px;overflow:auto;"></div> <script type="text/javascript" language="javascript" charset="utf-8"> // <![CDATA[ new Autocompleter.Local('id_%s','id_%supdate', %s, { fullSearch: true, partialSearch: true, frequency:0.001 %s %s }); // ]]> </script>""" % (name, name, value, flatatt(self.attrs), name, name, name, values, minChars, tokens)
def __unicode__(self): return smart_unicode(self.title or self.get_default_title())