def apercu_contenu(self, message): return Truncator(message.message).chars(40, truncate='...')
def __str__(self): #Truncator 工具类,这是将一个长字符串截取为任意长度字符的简便方法 truncated_message = Truncator(self.message) return truncated_message.chars(30)
def apercu_title(self, article): return Truncator(article.title).chars(30, truncate='...')
def log_name(self): # Required by task_log return Truncator(self.url).chars(32)
def transform_description_short(self, obj, value): return Truncator(value).chars(160)
def truncated_message_id(self, instance): if instance.message_id: return Truncator(instance.message_id[1:-1]).chars(10) return str(instance.id)
def get_teaser(self, words=6): """ Renvoyer une introduction du corps du commentaire """ return striptags(Truncator(self.body).words(words))
def get_list(self, instance): return [(c.id, c.name, Truncator(c.presentation).words(30)) for c in instance.candidate_set.all()]
def export_view(self, request, form_url=''): """The 'export' admin view for this model.""" info = self.opts.app_label, self.opts.model_name if not self.has_export_permission(request): raise PermissionDenied form = SubmissionExportForm(data=request.POST if request.method == 'POST' else None) if form.is_valid(): data = form.cleaned_data queryset = self.get_queryset(request) \ .filter(plugin_id=data.get('form')) \ .select_related('created_by', 'plugin', ) from_date, to_date = data.get('from_date'), data.get('to_date') headers = data.get('headers', []) if from_date: queryset = queryset.filter(creation_date__gte=from_date) if to_date: queryset = queryset.filter(creation_date__lt=to_date + datetime.timedelta(days=1)) if not queryset.exists(): message = _('No matching %s found for the given criteria. ' 'Please try again.') % self.opts.verbose_name_plural self.message_user(request, message, level=messages.WARNING) if request.is_ajax(): data = { 'reloadBrowser': True, 'submissionCount': 0, } return JsonResponse(data) return redirect('admin:%s_%s_export' % info) latest_submission = queryset[:1].get() dataset = Dataset(title=Truncator(latest_submission.plugin.name).chars(31)) if not headers: headers = [field['label'].strip() for field in latest_submission.form_data] for submission in queryset: for field in submission.form_data: label = field['label'].strip() if label not in headers: headers.append(label) if request.is_ajax(): data = { 'reloadBrowser': False, 'submissionCount': queryset.count(), 'availableHeaders': headers, } return JsonResponse(data) headers.extend(['Submitted By', 'Submitted on', 'Sender IP', 'Referrer URL']) dataset.headers = headers def humanize(field): value = field['value'] field_type = field['type'] if value in (None, '', [], (), {}): return None if field_type == 'checkbox': value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No'))) if field_type == 'checkbox_multiple': value = ', '.join(list(value)) return value for submission in queryset: row = [None] * len(headers) for field in submission.form_data: label = field['label'].strip() if label in headers: row[headers.index(label)] = humanize(field) row[-4] = force_text(submission.created_by or _('Unknown')) row[-3] = submission.creation_date.strftime( settings.DJANGOCMS_FORMS_DATETIME_FORMAT) row[-2] = submission.ip row[-1] = submission.referrer dataset.append(row) mimetype = { 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'csv': 'text/csv', 'html': 'text/html', 'yaml': 'text/yaml', 'json': 'application/json', } file_type = data.get('file_type', 'xlsx') filename = settings.DJANGOCMS_FORMS_EXPORT_FILENAME.format( form_name=slugify(latest_submission.plugin.name)) filename = timezone.now().strftime(filename) filename = '%s.%s' % (filename, file_type) response = HttpResponse( getattr(dataset, file_type), { 'content_type': mimetype.get(file_type, 'application/octet-stream') }) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response # Wrap in all admin layout fieldsets = ((None, {'fields': form.fields.keys()}),) adminform = AdminForm(form, fieldsets, {}, model_admin=self) media = self.media + adminform.media context = { 'title': _('Export %s') % force_text(self.opts.verbose_name_plural), 'adminform': adminform, 'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), 'media': mark_safe(media), 'errors': AdminErrorList(form, ()), 'app_label': self.opts.app_label, } return self.render_export_form(request, context, form_url)
def upload(self, data, owner, upload_size=0): """Use cleaned form data to populate an unsaved upload record. Once, each upload was just one file, so all we had to do was attach its name and type to the upload, where we could display it. Since multifile and geopackage supported were added, the required behavior depends on what we find in the upload. That is what this method is for. For example, it looks at an upload and tries to come up with a reasonably mnemonic name, or else set name to None to mean there was no obvious option. """ from osgeo_importer.models import UploadedData from django.db.models import Sum # Do not save here, we want to leave control of that to the caller. upload = UploadedData.objects.create(user=owner) upload.size = upload_size # Get a list of paths for files in this upload. paths = [item.name for item in data] # If there are multiple paths, see if we can boil them down to a # smaller number of representative paths (ideally, just one). if len(paths) > 1: # Group paths by common pre-extension prefixes groups = collections.defaultdict(list) for path in paths: group_name = os.path.splitext(path)[0] groups[group_name].append(path) # Check each group for "leaders" - a special filename like "a.shp" # which can be understood to represent other files in the group. # Map from each group name to a list of leaders in that group. leader_exts = ["shp"] group_leaders = {} for group_name, group in groups.items(): leaders = [ path for path in group if any( path.endswith(ext) for ext in leader_exts) ] if leaders: group_leaders[group_name] = leaders # Rebuild paths: leaders + paths without leaders to represent them leader_paths = [] for leaders in group_leaders.values(): leader_paths.extend(leaders) orphan_paths = [] for group_name, group in groups.items(): if group_name not in group_leaders: orphan_paths.extend(group) paths = leader_paths + orphan_paths max_length = UploadedData._meta.get_field('name').max_length # If no data, just return the instance. if not paths: name = None file_type = None # If we just have one path, that's a reasonable name for the upload. # We want this case to happen as frequently as reasonable, so that we # can set one reasonable name and file_type for the whole upload. elif len(paths) == 1: path = paths[0] basename = os.path.basename(path) name = Truncator(basename).chars(max_length) file_type = self.get_file_type(path) # Failing that, see if we can represent all the important paths within # the available space, making a meaningful mnemonic that isn't # misleading even though there isn't one obvious name. But if we can't # even do that, no use generating misleading or useless strings here, # just pass a None and let the frontend handle the lack of information. else: basenames = sorted(os.path.basename(path) for path in paths) name = ", ".join(basenames) if len(name) > max_length: logger.warning( "rejecting upload name for length: {0!r} {1} > {2}".format( name, len(name), max_length)) name = None file_type = None upload.name = name upload.file_type = file_type return upload
def short_description(self, ocean): return Truncator(ocean.description).words(100, truncate=' ...')
def truncate_words(s, num, end_text='...'): truncate = end_text and ' %s' % end_text or '' return Truncator(s).words(num, truncate=truncate)
def __init__(self, instance, user, *args, **kwargs): super(MovePostForm, self).__init__(*args, **kwargs) self.instance = instance self.user = user self.post = self.instance self.category, self.forum, self.topic = self.post.get_parents() if not self.post.is_topic_head: # we do not move an entire topic but a part of it's posts. Let's select those posts. self.posts_to_move = Post.objects.filter( created__gte=self.post.created, topic=self.topic).order_by('created', 'pk') # if multiple posts exists with the same created datetime, it's important to keep the # same order and do not move some posts which could be "before" our post. # We can not just filter by adding `pk__gt=self.post.pk` because we could exclude # some posts if for some reasons, a lesser pk has a greater "created" datetime # Most of the time, we just do one extra request to be sure the first post is # the wanted one first_pk = self.posts_to_move.values_list('pk', flat=True)[0] while first_pk != self.post.pk: self.posts_to_move = self.posts_to_move.exclude(pk=first_pk) first_pk = self.posts_to_move.values_list('pk', flat=True)[0] i = 0 choices = [] for post in self.posts_to_move[1:]: # all except the current one i += 1 bvars = { 'author': util.get_pybb_profile(post.user).get_display_name(), 'abstract': Truncator(post.body_text).words(8), 'i': i } label = _('%(i)d (%(author)s: "%(abstract)s")') % bvars choices.append((i, label)) choices.insert(0, (0, _('None'))) choices.insert(0, (-1, _('All'))) self.fields['number'] = forms.TypedChoiceField( label=ugettext_lazy('Number of following posts to move with'), choices=choices, required=True, coerce=int, ) # we move the entire topic, so we want to change it's forum. # So, let's exclude the current one # get all forum where we can move this post (and the others) move_to_forums = permissions.perms.filter_forums( self.user, Forum.objects.all()) if self.post.is_topic_head: # we move the entire topic, so we want to change it's forum. # So, let's exclude the current one move_to_forums = move_to_forums.exclude(pk=self.forum.pk) last_cat_pk = None choices = [] for forum in move_to_forums.order_by('category__position', 'position', 'name'): if not permissions.perms.may_create_topic(self.user, forum): continue if last_cat_pk != forum.category.pk: last_cat_pk = forum.category.pk choices.append(('%s' % forum.category, [])) if self.forum.pk == forum.pk: name = '%(forum)s (forum of the current post)' % { 'forum': self.forum } else: name = '%s' % forum choices[-1][1].append((forum.pk, name)) self.fields['move_to'] = forms.ChoiceField( label=ugettext_lazy('Move to forum'), initial=self.forum.pk, choices=choices, required=True, ) self.fields['name'] = forms.CharField(label=_('New subject'), initial=self.topic.name, max_length=255, required=True) if permissions.perms.may_edit_topic_slug(self.user): self.fields['slug'] = forms.CharField(label=_('New topic slug'), initial=self.topic.slug, max_length=255, required=False)
def __str__(self): return Truncator(strip_tags(self.body).replace('­', '')).words( 3, truncate="...")
def apercu_contenu(self, article): """ Retourne les 40 premiers caractères du contenu de l'article, suivi de points de suspension si le texte est plus long. """ return Truncator(article.contenu_post).chars(40, truncate='...')
def action_desc(action, full_url): desc = markdownify(strip_tags(action.description)) desc = Truncator(desc).words(30, html=True, truncate=' …') desc += f"<p><br><a href=\"{full_url}\">Full Event Details</a></p>" desc = urlquote_plus(desc) return desc
def import_entries(self, feed_entries): """Import entries""" for feed_entry in feed_entries: self.write_out('> %s... ' % feed_entry.title) if feed_entry.get('publised_parsed'): creation_date = datetime(*feed_entry.published_parsed[:6]) if settings.USE_TZ: creation_date = timezone.make_aware( creation_date, timezone.utc) else: creation_date = timezone.now() slug = slugify(feed_entry.title)[:255] if Entry.objects.filter(creation_date__year=creation_date.year, creation_date__month=creation_date.month, creation_date__day=creation_date.day, slug=slug): self.write_out( self.style.NOTICE('SKIPPED (already imported)\n')) continue categories = self.import_categories(feed_entry) entry_dict = { 'title': feed_entry.title[:255], 'content': feed_entry.description, 'excerpt': feed_entry.get('summary'), 'status': PUBLISHED, 'creation_date': creation_date, 'start_publication': creation_date, 'last_update': timezone.now(), 'slug': slug } if not entry_dict['excerpt'] and self.auto_excerpt: entry_dict['excerpt'] = Truncator( strip_tags(feed_entry.description)).words(50) if self.tags: entry_dict['tags'] = self.import_tags(categories) entry = Entry(**entry_dict) entry.save() entry.categories.add(*categories) entry.sites.add(self.SITE) if self.image_enclosure: for enclosure in feed_entry.enclosures: if ('image' in enclosure.get('type') and enclosure.get('href')): img_tmp = NamedTemporaryFile(delete=True) img_tmp.write(urlopen(enclosure['href']).read()) img_tmp.flush() entry.image.save(os.path.basename(enclosure['href']), File(img_tmp)) break if self.default_author: entry.authors.add(self.default_author) elif feed_entry.get('author_detail'): try: author = Author.objects.create_user( slugify(feed_entry.author_detail.get('name')), feed_entry.author_detail.get('email', '')) except IntegrityError: author = Author.objects.get( username=slugify(feed_entry.author_detail.get('name'))) entry.authors.add(author) self.write_out(self.style.ITEM('OK\n'))
def __str__(self): return Truncator(self.title).words(6, truncate="...")
def label_for_value(self, value): key = self.rel.get_related_field().name obj = self.rel.to._default_manager.get(**{key: value}) return Truncator(obj).words(14, truncate='...')
def __str__(self): return "{0}>{1}:{2}".format(self.obfuscated_sender, self.obfuscated_recipient, Truncator(self.subject).words(5))
def description_shortened(self, instance): return Truncator(instance.description.split('\n')[0]).chars(200)
def get_identifier(cls, obj): identifier = super(BootstrapTabPanePlugin, cls).get_identifier(obj) content = obj.glossary.get('tab_title', '') if content: content = Truncator(content).words(3, truncate=' ...') return format_html('{0}{1}', identifier, content)
def save(self, *args, **kwargs): ''' The following code will populate our indexed_custom search text with the latest model data before we save. ''' search_text = str(self.id) search_text += " " + intcomma(self.id) if self.description: search_text += " " + self.description if self.customer: if self.customer.organization: search_text += " " + self.customer.organization.name if self.customer.given_name: search_text += " " + self.customer.given_name if self.customer.middle_name: search_text += " " + self.customer.middle_name if self.customer.last_name: search_text += " " + self.customer.last_name if self.customer.email: search_text += " " + self.customer.email if self.customer.telephone: search_text += " " + phonenumbers.format_number(self.customer.telephone, phonenumbers.PhoneNumberFormat.NATIONAL) search_text += " " + phonenumbers.format_number(self.customer.telephone, phonenumbers.PhoneNumberFormat.INTERNATIONAL) search_text += " " + phonenumbers.format_number(self.customer.telephone, phonenumbers.PhoneNumberFormat.E164) if self.customer.other_telephone: search_text += " " + phonenumbers.format_number(self.customer.other_telephone, phonenumbers.PhoneNumberFormat.NATIONAL) search_text += " " + phonenumbers.format_number(self.customer.other_telephone, phonenumbers.PhoneNumberFormat.INTERNATIONAL) search_text += " " + phonenumbers.format_number(self.customer.other_telephone, phonenumbers.PhoneNumberFormat.E164) if self.customer.description: search_text += " " + self.customer.description search_text += " " + self.customer.get_postal_address() if self.associate: if self.associate.given_name: search_text += " " + self.associate.given_name if self.associate.middle_name: search_text += " " + self.associate.middle_name if self.associate.last_name: search_text += " " + self.associate.last_name if self.associate.email: search_text += " " + self.associate.email if self.associate.telephone: search_text += " " + phonenumbers.format_number(self.associate.telephone, phonenumbers.PhoneNumberFormat.NATIONAL) search_text += " " + phonenumbers.format_number(self.associate.telephone, phonenumbers.PhoneNumberFormat.INTERNATIONAL) search_text += " " + phonenumbers.format_number(self.associate.telephone, phonenumbers.PhoneNumberFormat.E164) if self.associate.other_telephone: search_text += " " + phonenumbers.format_number(self.associate.other_telephone, phonenumbers.PhoneNumberFormat.NATIONAL) search_text += " " + phonenumbers.format_number(self.associate.other_telephone, phonenumbers.PhoneNumberFormat.INTERNATIONAL) search_text += " " + phonenumbers.format_number(self.associate.other_telephone, phonenumbers.PhoneNumberFormat.E164) if self.associate.description: search_text += " " + self.associate.description search_text += " " + self.associate.get_postal_address() if self.invoice_ids: search_text += " " + str(self.invoice_ids) self.indexed_text = Truncator(search_text).chars(2047) ''' Run our `save` function. ''' super(WorkOrder, self).save(*args, **kwargs)
def title (self): truncator = Truncator(self.topics) return truncator.words(12)
def label_for_value(self, other_model, rel_name, value): try: obj = other_model._default_manager.get(**{rel_name: value}) return '%s' % escape(Truncator(obj).words(14, truncate='...')) except (ValueError, other_model.DoesNotExist): return ""
def get_title(self): if (self.header is None): return Truncator(strip_tags(self.text).replace('­', '')).words( 3, truncate="...") else: return self.header
def apercu_content(self, article): return Truncator(article.content).chars(40, truncate='...')
def truncate(self): """ Truncate the content with the Truncator object. """ return Truncator(self.content).words( self.max_words, self.more_string, html=True)
def __str__(self): truncated_message = Truncator(self.message) return truncated_message.chars(30)
def video_title(self, obj): return Truncator(obj.video.title).chars(50)