コード例 #1
0
ファイル: models.py プロジェクト: matllubos/django-security
def clean_body(body, max_lenght):
    cleaned_body = truncatechars(
        truncate_body(body, max_lenght), max_lenght + len(settings.SENSITIVE_DATA_REPLACEMENT)
    ) if max_lenght is not None else str(body)
    cleaned_body = hide_sensitive_data_body(remove_nul_from_string(cleaned_body)) if cleaned_body else cleaned_body
    cleaned_body = truncatechars(cleaned_body, max_lenght) if max_lenght else cleaned_body
    return cleaned_body
コード例 #2
0
ファイル: models.py プロジェクト: sputnikus/django-security
    def prepare_from_request(self, request):
        user = hasattr(request, 'user') and request.user.is_authenticated() and request.user or None
        path = truncatechars(request.path, 200)
        body = truncatechars(force_text(request.body[:LOG_REQUEST_BODY_LENGTH + 1],
                                        errors='replace'), LOG_REQUEST_BODY_LENGTH)

        return self.model(headers=get_headers(request), body=body, user=user, method=request.method.upper(),
                           path=path, queries=request.GET.dict(), is_secure=request.is_secure(),
                           ip=get_ip(request), request_timestamp=timezone.now())
コード例 #3
0
ファイル: base.py プロジェクト: sdsingh/horizon
    def get_data(self, datum):
        """
        Returns the final display data for this column from the given inputs.

        The return value will be either the attribute specified for this column
        or the return value of the attr:`~horizon.tables.Column.transform`
        method for this column.
        """
        datum_id = self.table.get_object_id(datum)

        if datum_id in self.table._data_cache[self]:
            return self.table._data_cache[self][datum_id]

        data = self.get_raw_data(datum)
        display_value = None

        if self.display_choices:
            display_value = [
                display for (value, display) in self.display_choices if value.lower() == (data or "").lower()
            ]

        if display_value:
            data = display_value[0]
        else:
            for filter_func in self.filters:
                data = filter_func(data)

        if data and self.truncate:
            data = truncatechars(data, self.truncate)

        self.table._data_cache[self][datum_id] = data

        return self.table._data_cache[self][datum_id]
コード例 #4
0
def chain_user_names(users, exclude_user, truncate=35):
    """Tag to return a truncated chain of user names."""
    if not users or not isinstance(exclude_user, get_user_model()):
        return ''
    return truncatechars(
        ', '.join(u'{}'.format(u) for u in users.exclude(pk=exclude_user.pk)),
        truncate)
コード例 #5
0
ファイル: programme.py プロジェクト: tracon/kompassi
    def paikkalize(self):
        if not self.is_using_paikkala:
            return None
        if self.paikkala_program:
            return self.paikkala_program

        assert self.can_paikkalize

        from django.template.defaultfilters import truncatechars
        from paikkala.models import Program as PaikkalaProgram, Row

        paikkala_room = self.room.paikkalize()
        meta = self.event.programme_event_meta

        self.paikkala_program = PaikkalaProgram.objects.create(
            event_name=self.event.name,
            name=truncatechars(self.title, PaikkalaProgram._meta.get_field('name').max_length),
            room=paikkala_room,
            require_user=True,
            reservation_end=self.start_time,
            invalid_after=self.end_time,
            max_tickets=0,
            automatic_max_tickets=True,
            max_tickets_per_user=meta.paikkala_default_max_tickets_per_user,
            max_tickets_per_batch=meta.paikkala_default_max_tickets_per_batch,
        )
        self.save()

        self.paikkala_program.rows.set(Row.objects.filter(zone__room=paikkala_room))

        return self.paikkala_program
コード例 #6
0
ファイル: email.py プロジェクト: 40a/openduty
    def notify(self, notification):

        gmail_user = self.__config['user']
        gmail_pwd = self.__config['password']
        truncate_length = int(self.__config.get('max_subject_length', 100))
        FROM = self.__config['user']
        TO = [notification.user_to_notify.email]
        try:
            SUBJECT = "Openduty Incident Report - {0}".format(notification.incident.description)
        except:
            SUBJECT = notification.message
        if truncate_length:
            SUBJECT = truncatechars(SUBJECT, truncate_length)
        TEXT =  notification.message
        message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
            """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
        try:
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.starttls()
            server.ehlo()
            server.login(gmail_user, gmail_pwd)
            server.sendmail(FROM, TO, message)
            server.close()
            print 'successfully sent the mail'
        except:
            print "failed to send mail"
コード例 #7
0
ファイル: models.py プロジェクト: WSULib/readux
 def display_label(self):
     '''Display label, for use in html titles, twitter/facebook metadata, etc.
     Truncates the title to the first 150 characters, and includes volume information
     if any.
     '''
     vol = ' [%s]' % self.volume if self.volume else ''
     return '%s%s' % (truncatechars(self.title.rstrip(), 150), vol)
コード例 #8
0
ファイル: util.py プロジェクト: LACNIC/internal-stats-portal
def truncate_text(text, length):
    if text:
        if len(text) > length:
            return truncatechars(text, length)
        else:
            return text
    return ""
コード例 #9
0
ファイル: models.py プロジェクト: codesyntax/bitakora
 def getTweetText(self):
     current_site = Site.objects.get_current()
     if self.blog.user.twitter_id:
         return "[%s] %s %s%s @%s" % (
             truncatechars(self.blog.name, 20),
             truncatechars(self.title, 40),
             current_site,
             self.get_absolute_url(),
             self.blog.user.twitter_id,
         )
     return "[%s] %s %s%s" % (
         truncatechars(self.blog.name, 20),
         truncatechars(self.title, 50),
         current_site,
         self.get_absolute_url(),
     )
コード例 #10
0
ファイル: models.py プロジェクト: ronrest/reviews_app
 def condensed_review(self, max_len=40):
     """
     Return a condensed version of the review so that it does not exceed some
     specified length. Includes ellipses to indicate that the text continues
     if it is longer than the max length.
     """
     return truncatechars(self.review, max_len)
コード例 #11
0
ファイル: __init__.py プロジェクト: DrMeers/djangocon-au-2013
def apps():
    HEADING = 'Apps'
    PAGE_SIZE = 5
    heading(HEADING)
    command("github.search('django')", wait=True)
    repositories = github.search('django')['repositories']
    for index, repository in enumerate(repositories):
        updated = parse_datetime(
            repository['pushed_at']).replace(tzinfo=timezone.utc)
        age = (timezone.now() - updated)
        if age < datetime.timedelta(30*2):
            age_colour = 'green'
        elif age < datetime.timedelta(30*6):
            age_colour = 'blue'
        elif age < datetime.timedelta(365):
            age_colour = 'magenta'
        else:
            age_colour = 'red'
        comment(
            u'{0[username]}:{1} - {2} - {3}'.format(
                repository,
                coloured(coloured(repository['name'], 'bold'), 'black'),
                coloured(u'\u2605 {0[watchers]}'.format(repository), 'yellow'),
                coloured(timesince(updated), age_colour),
            ),
            coloured(truncatechars(repository['description'], 70), 'grey'),
        )
        if index > 0 and index % PAGE_SIZE == 0:
            heading(HEADING)
コード例 #12
0
ファイル: admin.py プロジェクト: DjangoBD/djangocms-comments
 def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
     extra_context = extra_context or {}
     comment = self.get_object(request, unquote(object_id))
     if comment is not None:
         extra_context['user_agent'] = get_user_agent(comment.user_agent) or truncatechars(comment.user_agent, 60)
     return super(CommentAdmin, self).changeform_view(request, object_id=object_id, form_url=form_url,
                                                      extra_context=extra_context)
コード例 #13
0
ファイル: models.py プロジェクト: SafaAlfulaij/pootle
 def get_last_created_unit_info(self):
     return {
         "display_datetime": dateformat.format(self.creation_time),
         "creation_time": int(dateformat.format(self.creation_time, 'U')),
         "unit_source": truncatechars(self, 50),
         "unit_url": self.get_translate_url(),
     }
コード例 #14
0
    def __unicode__(self):

        try:
            return u'{0} "{1}" by {2}'.format(self.kwargs['func'].capitalize(), truncatechars(self.kwargs['tweet'], 50),
                                              self.kwargs['screen_name'])
        except KeyError:
            return u'%s' % self.func
コード例 #15
0
ファイル: email.py プロジェクト: AlexTsr/openduty
 def notify(self, notification):
     smtp_user = self.__config['user']
     smtp_pwd = self.__config['password']
     smtp_host = self.__config['host']
     smtp_port = self.__config['port']
     truncate_length = int(self.__config.get('max_subject_length', 100))
     FROM = self.__config['from']
     TO = [notification.user_to_notify.email]
     try:
         SUBJECT = "Openduty Incident Report - {0}".format(notification.incident.description)
     except:
         SUBJECT = notification.message
     if truncate_length:
         SUBJECT = truncatechars(SUBJECT, truncate_length)
     TEXT =  notification.message
     try:
         server = smtplib.SMTP(smtp_host, smtp_port)
         server.starttls()
         server.ehlo()
         server.login(smtp_user, smtp_pwd)
         server.sendmail(FROM, TO, TEXT)
         server.close()
         print 'successfully sent the mail'
     except:
         print "failed to send mail"
コード例 #16
0
ファイル: rfnumplan.py プロジェクト: night-crawler/rfnumplan
    def handle_list_plan_ranges(self, args, options):
        ranges = self.get_plan_ranges_queryset(options)
        ranges = self.filter_plan_ranges_queryset(ranges, options)

        fields = ['numbering_plan__prefix', 'prefix', 'range_start', 'range_end', 'range_capacity', 'operator__name',
                  'region__name']
        header = [_('#'), _('###'), _('Start'), _('End'), _('Capacity'), _('Operator'), _('Region')]
        ranges_data = []

        page = self.paginated(ranges.values(*fields), options)
        for r in page.object_list:
            r['range_start'] = str(r['range_start'])[1:]
            r['range_end'] = str(r['range_end'])[1:]
            r['operator__name'] = truncatechars(r['operator__name'], 40)
            ranges_data.append([r[field] for field in fields])

        data = [header, *ranges_data]
        if not options.get('page'):
            title = str(_('Numbering plan ranges [x%s]')) % page.paginator.count
        else:
            title = str(_('Numbering plan ranges [x%(count)s], page %(page)s of %(num_pages)s')) % {
                'count': page.paginator.count,
                'page': options.get('page'),
                'num_pages': page.paginator.num_pages
            }

        self.log(SingleTable(data, title=title).table, clr='DEFAULT')
コード例 #17
0
    def truncated_object_with_change_link(self, obj):

        related_field_name = [field_name for field_name in obj._meta.unique_together[0] if field_name != 'tag'][0]

        related_field = getattr(obj, related_field_name)

        return format_html('<a href="{}">{}</a>', get_admin_url(related_field), truncatechars(related_field, 160))
コード例 #18
0
ファイル: utils.py プロジェクト: DjangoLover/allmywishes
    def prepared_data(self):
        return {
            "title": truncatechars(self.obj["title"], 100),
            "description": self.obj["title"],
            "provider_name": self.obj["provider_name"],
            "image_src": self.get_main_image_src()

        }
コード例 #19
0
    def save(self, *args, **kwargs):
        if self.file:
            self.size = self.file.size

        if not self.name:
            self.name = truncatechars(self.file.name, 80)

        super(Attachment, self).save(*args, **kwargs)
コード例 #20
0
ファイル: note.py プロジェクト: filipp/Servo
def note_saved(sender, instance, created, **kwargs):
    if created and instance.order:
        order = instance.order
        user = instance.created_by

        if user is not order.user:
            msg = truncatechars(instance.body, 75)
            order.notify("note_added", msg, user)
コード例 #21
0
ファイル: app.py プロジェクト: pizzapanther/NeutronBuilder
    def generate_summary(self, content):
        config = self.get_config()
        cleaned = striptags(content)
        if config["summary_count_type"] == "char":
            return truncatechars(cleaned, config["summary_count"])

        else:
            return truncatewords(cleaned, config["summary_count"])
コード例 #22
0
ファイル: dev.py プロジェクト: harvard-lil/perma
def test_internet_archive():
    from datetime import timedelta
    from django.utils import timezone
    import internetarchive
    from perma.models import Link
    from django.template.defaultfilters import truncatechars

    start_date = timezone.now() - timedelta(days=3)
    end_date = timezone.now() - timedelta(days=2)

    links = Link.objects.filter(
        internet_archive_upload_status="completed", creation_timestamp__range=(start_date, end_date)
    )

    guid_results = dict()
    all_results = dict()

    c = {"s3": {"access": settings.INTERNET_ARCHIVE_ACCESS_KEY, "secret": settings.INTERNET_ARCHIVE_SECRET_KEY}}
    internetarchive.get_session(config=c)

    for link in links:
        identifier = settings.INTERNET_ARCHIVE_IDENTIFIER_PREFIX + link.guid
        item = internetarchive.get_item(identifier)
        warc_name = "%s.warc.gz" % link.guid

        try:
            fnames = [f.name for f in internetarchive.get_files(identifier, glob_pattern="*gz")]
            guid_results["uploaded_file"] = warc_name in fnames
            if settings.INTERNET_ARCHIVE_COLLECTION == "test_collection":
                guid_results["collection"] = item.metadata["collection"] == settings.INTERNET_ARCHIVE_COLLECTION
            else:
                guid_results["collection"] = item.metadata["collection"][0] == settings.INTERNET_ARCHIVE_COLLECTION
            guid_results["title"] = item.metadata["title"] == "%s: %s" % (
                link.guid,
                truncatechars(link.submitted_title, 50),
            )
            guid_results["mediatype"] = item.metadata["mediatype"] == "web"
            guid_results["description"] = item.metadata["description"] == "Perma.cc archive of %s created on %s." % (
                link.submitted_url,
                link.creation_timestamp,
            )
            guid_results["contributor"] = item.metadata["contributor"] == "Perma.cc"
            guid_results["submitted_url"] = item.metadata["submitted_url"] == link.submitted_url
            guid_results["perma_url"] = item.metadata["perma_url"] == "http://%s/%s" % (settings.HOST, link.guid)
            guid_results["external-identifier"] = item.metadata["external-identifier"] == "urn:X-perma:%s" % link.guid
            if link.organization:
                guid_results["organization"] = item.metadata["sponsor"] == "%s - %s" % (
                    link.organization,
                    link.organization.registrar,
                )

        except Exception as e:
            guid_results["error"] = e
            pass

        all_results[link.guid] = guid_results

    print all_results
コード例 #23
0
ファイル: models.py プロジェクト: matllubos/django-security
def truncate_json_data(data):
    if isinstance(data, dict):
        return {key: truncate_json_data(val) for key, val in data.items()}
    elif isinstance(data, list):
        return [truncate_json_data(val) for val in data]
    elif isinstance(data, str):
        return truncatechars(data, settings.LOG_JSON_STRING_LENGTH)
    else:
        return data
コード例 #24
0
    def truncated_label(self):
        if self.active:
            label_maxlength = self.active_label_maxlength
        else:
            label_maxlength = self.label_maxlength

        if label_maxlength:
            return defaultfilters.truncatechars(self.label, label_maxlength)
        return self.label
コード例 #25
0
    def display_topic(self, obj):
        """ """

        return format_html(
            '<a href="{}">{}</a><br /><b>{}</b> >> {}',
            obj.get_admin_url(),
            truncatechars(obj.subject, 75),
            obj.user,
            convert_date_to_django_date_format(obj.created),
        )
コード例 #26
0
ファイル: views.py プロジェクト: fesp21/hatch
    def get_user_tweet_text(cls, request, vision):
        vision_url = cls.get_vision_url(request, vision)
        service = cls.get_twitter_service()
        url_length = service.get_url_length(vision_url)

        vision_length = 140 - url_length - 1
        return ''.join([
            truncatechars(vision.text, vision_length),
            ' ', vision_url
        ])
コード例 #27
0
ファイル: views.py プロジェクト: lockwooddev/backbone-banter
    def get(self, request, *args, **kwargs):
        catalog = ChanApi.get_catalog(kwargs.get('board'))
        for page in catalog:
            for thread in page['threads']:
                subject = thread.get('sub')
                comment = thread.get('com')

                thread['title'] = strip_tags(subject) if subject else ''
                thread['comment'] = truncatechars(strip_tags(comment), 180) if comment else ''
        return JsonResponse(catalog, safe=False)
コード例 #28
0
 def add_group_breadcrumb_item(self, group, active=False):
     self.add_headeritem_object(devilry_crmenu.BreadcrumbMenuItem(
         label=defaultfilters.truncatechars(self.get_group_label(group), 25),
         url=reverse_cradmin_url(
             instanceid='devilry_group_student',
             appname='feedbackfeed',
             roleid=group.id,
             viewname=crapp.INDEXVIEW_NAME,
         ),
         active=active
     ))
コード例 #29
0
ファイル: admin.py プロジェクト: 11m09d/weixin_market
 def save_model(self, request, obj, form, change):
     """
     Sends a tweet with the title/short_url if applicable.
     """
     super(TweetableAdminMixin, self).save_model(request, obj, form, change)
     if Api and request.POST.get("send_tweet", False):
         auth_settings = get_auth_settings()
         obj.set_short_url()
         message = truncatechars(obj, 140 - len(obj.short_url) - 1)
         api = Api(*auth_settings)
         api.PostUpdate("%s %s" % (message, obj.short_url))
コード例 #30
0
ファイル: views.py プロジェクト: fesp21/hatch
    def get_tweet_text(self, request, reply):
        app_username = settings.TWITTER_USERNAME
        if not app_username.startswith('@'):
            app_username = '******' + app_username

        if app_username not in reply.text:
            tweet_text = app_username + ' ' + reply.text
        else:
            tweet_text = reply.text

        return truncatechars(tweet_text, 140)
コード例 #31
0
def truncated_kwargs(self):
    return truncatechars(self.kwargs, 100)
コード例 #32
0
ファイル: models.py プロジェクト: zefredz/getopinionated
 def __unicode__(self):
     delegates = ','.join(unicode(d) for d in self.delegates.all())
     delegates = truncatechars(delegates, 40)
     return u"Proxy of {} to ({})".format(self.delegating, delegates)
コード例 #33
0
ファイル: models.py プロジェクト: zefredz/getopinionated
 def tags_str(self):
     """ string representation of tags """
     tags = ','.join(unicode(d) for d in self.tags.all())
     tags = truncatechars(tags, 40)
     return tags
コード例 #34
0
ファイル: cradmin.py プロジェクト: appressoas/cradmin_legacy
 def get_descriptiontext_for_role(self, role):
     """
     Get a short description of the given ``role``.
     Remember that the role is a Site.
     """
     return truncatechars(role.description, 100)
コード例 #35
0
 def result_(self, obj):
     return truncatechars(str(obj.result), 32)
コード例 #36
0
ファイル: models.py プロジェクト: leoneg/estel
 def short_about(self):
     return truncatechars(self.about, 100)
コード例 #37
0
 def truncated_text(self, obj):
     return truncatechars(obj.text, 60)
コード例 #38
0
ファイル: models.py プロジェクト: fesp21/SocAIty-Website
 def truncated_message(self):
     return truncatechars(self.message, 50)
コード例 #39
0
ファイル: models.py プロジェクト: ChristianSB24/Blog
 def Entry(self):
     return truncatechars(self.entry, 50)
コード例 #40
0
 def short_content(self):
     return truncatechars(self.content, 300)
コード例 #41
0
ファイル: feeds.py プロジェクト: NataliSemi/mysite
 def item_description(self, item):
     return truncatechars(item.body, 30)
コード例 #42
0
def make_review_request_context(request,
                                review_request,
                                extra_context={},
                                is_diff_view=False):
    """Returns a dictionary for template contexts used for review requests.

    The dictionary will contain the common data that is used for all
    review request-related pages (the review request detail page, the diff
    viewer, and the screenshot pages).

    For convenience, extra data can be passed to this dictionary.
    """
    if review_request.repository:
        upload_diff_form = UploadDiffForm(review_request, request=request)
        scmtool = review_request.repository.get_scmtool()
    else:
        upload_diff_form = None
        scmtool = None

    if 'blocks' not in extra_context:
        extra_context['blocks'] = list(review_request.blocks.all())

    tabs = [
        {
            'text': _('Reviews'),
            'url': review_request.get_absolute_url(),
        },
    ]

    draft = review_request.get_draft(request.user)

    if ((draft and draft.diffset_id)
            or (hasattr(review_request, '_diffsets')
                and len(review_request._diffsets) > 0)):
        has_diffs = True
    else:
        # We actually have to do a query
        has_diffs = DiffSet.objects.filter(
            history__pk=review_request.diffset_history_id).exists()

    if has_diffs:
        tabs.append({
            'active':
            is_diff_view,
            'text':
            _('Diff'),
            'url': (local_site_reverse('view-diff',
                                       args=[review_request.display_id],
                                       local_site=review_request.local_site) +
                    '#index_header'),
        })

    review_request_details = extra_context.get('review_request_details',
                                               review_request)
    social_page_description = truncatechars(
        review_request_details.description.replace('\n', ' '), 300)

    context = dict(
        {
            'mutable_by_user':
            review_request.is_mutable_by(request.user),
            'status_mutable_by_user':
            review_request.is_status_mutable_by(request.user),
            'review_request':
            review_request,
            'upload_diff_form':
            upload_diff_form,
            'scmtool':
            scmtool,
            'tabs':
            tabs,
            'social_page_description':
            social_page_description,
            'social_page_url':
            build_server_url(request.path, request=request),
        }, **extra_context)

    if ('review_request_visit' not in context
            and request.user.is_authenticated()):
        # The main review request view will already have populated this, but
        # other related views (like the diffviewer) don't.
        context['review_request_visit'] = \
            ReviewRequestVisit.objects.get_or_create(
                user=request.user,
                review_request=review_request)[0]

    return context
コード例 #43
0
 def short_description(self):
     return truncatechars(self.description, 20)
コード例 #44
0
ファイル: dev.py プロジェクト: weddingjuma/perma
def test_internet_archive():
    from datetime import timedelta
    from django.utils import timezone
    import internetarchive
    from perma.models import Link
    from django.template.defaultfilters import truncatechars

    start_date = timezone.now() - timedelta(days=3)
    end_date = timezone.now() - timedelta(days=2)

    links = Link.objects.filter(internet_archive_upload_status="completed",
                                creation_timestamp__range=(start_date,
                                                           end_date))

    guid_results = dict()
    all_results = dict()

    c = {
        "s3": {
            "access": settings.INTERNET_ARCHIVE_ACCESS_KEY,
            "secret": settings.INTERNET_ARCHIVE_SECRET_KEY
        }
    }
    internetarchive.get_session(config=c)

    for link in links:
        identifier = settings.INTERNET_ARCHIVE_IDENTIFIER_PREFIX + link.guid
        item = internetarchive.get_item(identifier)
        warc_name = "%s.warc.gz" % link.guid

        try:
            fnames = [
                f.name for f in internetarchive.get_files(identifier,
                                                          glob_pattern="*gz")
            ]
            guid_results["uploaded_file"] = warc_name in fnames
            if settings.INTERNET_ARCHIVE_COLLECTION == 'test_collection':
                guid_results["collection"] = item.metadata[
                    "collection"] == settings.INTERNET_ARCHIVE_COLLECTION
            else:
                guid_results["collection"] = item.metadata["collection"][
                    0] == settings.INTERNET_ARCHIVE_COLLECTION
            guid_results["title"] = item.metadata["title"] == "%s: %s" % (
                link.guid, truncatechars(link.submitted_title, 50))
            guid_results["mediatype"] = item.metadata["mediatype"] == "web"
            guid_results["description"] = item.metadata[
                "description"] == "Perma.cc archive of %s created on %s." % (
                    link.submitted_url,
                    link.creation_timestamp,
                )
            guid_results["contributor"] = item.metadata[
                "contributor"] == "Perma.cc"
            guid_results["submitted_url"] = item.metadata[
                "submitted_url"] == link.submitted_url
            guid_results["perma_url"] = item.metadata[
                "perma_url"] == "http://%s/%s" % (settings.HOST, link.guid)
            guid_results["external-identifier"] = item.metadata[
                "external-identifier"] == "urn:X-perma:%s" % link.guid
            if link.organization:
                guid_results["organization"] = item.metadata[
                    "sponsor"] == "%s - %s" % (link.organization,
                                               link.organization.registrar)

        except Exception as e:
            guid_results["error"] = e
            pass

        all_results[link.guid] = guid_results

    print all_results
コード例 #45
0
 def property_link_target_original(self):
     return truncatechars(self.link_target_original, 50)
コード例 #46
0
    def truncated_original_url(self, url_object):
        """Обрезает оригинальный URL до 50 символов,
		для лучшего отображения в админке, в случае если URL
		очень длинный"""
        return truncatechars(url_object.original_url, 50)
コード例 #47
0
 def kwargs_(self, obj):
     return truncatechars(str(obj.kwargs), 32)
コード例 #48
0
ファイル: models.py プロジェクト: YESLTD/pootle
    def get_submission_info(self):
        """Returns a dictionary describing the submission.

        The dict includes the user (with link to profile and gravatar),
        a type and translation_action_type describing the action performed,
        and when it was performed.
        """
        result = {}

        if self.unit is not None:
            result.update({
                'unit_source': truncatechars(self.unit, 50),
                'unit_url': self.unit.get_translate_url(),
            })

            if self.quality_check is not None:
                check_name = self.quality_check.name
                result.update({
                    'check_name':
                    check_name,
                    'check_display_name':
                    check_names.get(check_name, check_name),
                    'checks_url':
                    reverse('pootle-checks-descriptions'),
                })
        # Sadly we may not have submitter information in all the
        # situations yet
        # TODO check if it is true
        if self.submitter:
            displayuser = self.submitter
        else:
            User = get_user_model()
            displayuser = User.objects.get_nobody_user()

        result.update({
            "profile_url": displayuser.get_absolute_url(),
            "email": displayuser.email_hash,
            "displayname": displayuser.display_name,
            "username": displayuser.username,
            "display_datetime": dateformat.format(self.creation_time),
            "type": self.type,
            "mtime": int(dateformat.format(self.creation_time, 'U')),
        })

        # TODO Fix bug 3011 and remove the following code related to
        # TranslationActionTypes.

        if self.type in SubmissionTypes.EDIT_TYPES:
            translation_action_type = None
            try:
                if self.field == SubmissionFields.TARGET:
                    if self.new_value != '':
                        # Note that we analyze current unit state:
                        # if this submission is not last unit state
                        # can be changed
                        if self.unit.state == TRANSLATED:

                            if self.old_value == '':
                                translation_action_type = \
                                    TranslationActionTypes.TRANSLATED
                            else:
                                translation_action_type = \
                                    TranslationActionTypes.EDITED
                        elif self.unit.state == FUZZY:
                            if self.old_value == '':
                                translation_action_type = \
                                    TranslationActionTypes.PRE_TRANSLATED
                            else:
                                translation_action_type = \
                                    TranslationActionTypes.EDITED
                    else:
                        translation_action_type = \
                            TranslationActionTypes.REMOVED
                elif self.field == SubmissionFields.STATE:
                    # Note that a submission where field is STATE
                    # should be created before a submission where
                    # field is TARGET

                    translation_action_type = {
                        TRANSLATED: TranslationActionTypes.REVIEWED,
                        FUZZY: TranslationActionTypes.NEEDS_WORK
                    }.get(int(to_python(self.new_value)), None)

            except AttributeError:
                return result

            if translation_action_type is not None:
                result['translation_action_type'] = translation_action_type

        return result
コード例 #49
0
 def testu_laburra(self):
     return truncatechars(self.text, 80)
コード例 #50
0
ファイル: admin.py プロジェクト: nsiregar/kuma
 def title_short(self, obj):
     return truncatechars(obj.title, self.MAX_LENGTH)
コード例 #51
0
def render_plain(context, post, truncate=None):
    result = mark_safe(markdown_plain(post.text))
    if truncate:
        result = truncatechars(result, truncate)
    return result
コード例 #52
0
 def short_comment(self, criteria):
     return truncatechars(criteria.comment, 64)
コード例 #53
0
 def short_comment(self, evaluation):
     return truncatechars(evaluation.comment, 64)
コード例 #54
0
 def get_meta_description(self, **kwargs):
     request = kwargs.get('request')
     s = MLStripper()
     s.feed(mark_safe(render_placeholder(request, self.contents).html))
     return truncatechars(s.get_data(), 250)
コード例 #55
0
ファイル: admin.py プロジェクト: nsiregar/kuma
 def slug_short(self, obj):
     return truncatechars(obj.slug, self.MAX_LENGTH)
コード例 #56
0
 def short_comment(self):
     return truncatechars(self.comment, 60)
コード例 #57
0
 def _resumen(self):
     return truncatechars(self.resumen, 150)
コード例 #58
0
ファイル: models.py プロジェクト: CjS77/QuickAds
 def short_description(self):
     return truncatechars(self.message, 35)
コード例 #59
0
ファイル: text.py プロジェクト: szymi-/saleor
def generate_seo_description(html_text: str, max_length: int):
    """Strips HTML tags and whitespaces from text,
    then trim the description."""
    text = strip_html(html_text, strip_whitespace=True)
    text = truncatechars(text, max_length)
    return text
コード例 #60
0
    def get_submission_message(self):
        """Returns a message describing the submission.

        The message includes the user (with link to profile and gravatar), a
        message describing the action performed, and when it was performed.
        """
        unit = {}
        source = {}

        if self.unit is not None:
            unit = {
                'source': escape(truncatechars(self.unit, 50)),
                'url': self.unit.get_translate_url(),
            }
            source = {
                'source_string':
                '<i><a href="%(url)s">%(source)s</a></i>' % unit,
            }

            if self.quality_check is not None:
                check_name = self.quality_check.name
                unit.update({
                    'check_name':
                    check_name,
                    'check_display_name':
                    check_names[check_name],
                    'checks_url':
                    reverse('pootle-staticpages-display',
                            args=['help/quality-checks']),
                })
                source.update({
                    'check_name':
                    '<a href="%(checks_url)s#%(check_name)s">'
                    '%(check_display_name)s</a>' % unit,
                })

        if (self.suggestion and self.type
                in (SubmissionTypes.SUGG_ACCEPT, SubmissionTypes.SUGG_REJECT)):
            displayuser = self.suggestion.reviewer
        else:
            # Sadly we may not have submitter information in all the
            # situations yet
            # TODO check if it is true
            if self.submitter:
                displayuser = self.submitter
            else:
                User = get_user_model()
                displayuser = User.objects.get_nobody_user()

        displayname = displayuser.display_name

        action_bundle = {
            "profile_url": displayuser.get_absolute_url(),
            "gravatar_url": displayuser.gravatar_url(20),
            "displayname": displayname,
            "username": displayuser.username,
            "date": self.creation_time,
            "isoformat_date": self.creation_time.isoformat(),
            "action": "",
        }

        msg = {
            SubmissionTypes.REVERT:
            _('reverted translation for %(source_string)s', source),
            SubmissionTypes.SUGG_ACCEPT:
            _('accepted suggestion for %(source_string)s', source),
            SubmissionTypes.SUGG_ADD:
            _('added suggestion for %(source_string)s', source),
            SubmissionTypes.SUGG_REJECT:
            _('rejected suggestion for %(source_string)s', source),
            SubmissionTypes.UPLOAD:
            _('uploaded a file'),
            SubmissionTypes.MUTE_CHECK:
            _('muted %(check_name)s for %(source_string)s', source),
            SubmissionTypes.UNMUTE_CHECK:
            _('unmmuted %(check_name)s for %(source_string)s', source),
        }.get(self.type, None)

        #TODO Look how to detect submissions for "sent suggestion", "rejected
        # suggestion"...

        #TODO Fix bug 3011 and replace the following code with the appropiate
        # one in the dictionary above.

        if msg is None:
            try:
                if self.field == SubmissionFields.TARGET:
                    if self.new_value != '':
                        # Note that we analyze current unit state:
                        # if this submission is not last unit state
                        # can be changed
                        if self.unit.state == TRANSLATED:
                            if self.old_value == '':
                                msg = _('translated %(source_string)s', source)
                            else:
                                msg = _('edited %(source_string)s', source)
                        elif self.unit.state == FUZZY:
                            if self.old_value == '':
                                msg = _('pre-translated %(source_string)s',
                                        source)
                            else:
                                msg = _('edited %(source_string)s', source)
                    else:
                        msg = _('removed translation for %(source_string)s',
                                source)
                elif self.field == SubmissionFields.STATE:
                    # Note that a submission where field is STATE
                    # should be created before a submission where
                    # field is TARGET
                    msg = {
                        TRANSLATED: _('reviewed %(source_string)s', source),
                        FUZZY: _('marked as fuzzy %(source_string)s', source)
                    }.get(int(to_python(self.new_value)), '')
                else:
                    msg = _('unknown action %(source_string)s', source)
            except AttributeError:
                return ''

        action_bundle['action'] = msg

        return mark_safe(
            u'<div class="last-action">'
            '  <a href="%(profile_url)s">'
            '    <img src="%(gravatar_url)s" />'
            '    <span title="%(username)s">%(displayname)s</span>'
            '  </a>'
            '  <span class="action-text">%(action)s</span>'
            '  <time class="extra-item-meta js-relative-date"'
            '    title="%(date)s" datetime="%(isoformat_date)s">&nbsp;'
            '  </time>'
            '</div>' % action_bundle)