Exemplo n.º 1
0
 def short(self):
     if self.day:
         return dateformat.format(self.lower_bound, "jS F Y")
     elif self.month:
         return dateformat.format(self.lower_bound, "F Y")
     else:
         return dateformat.format(self.lower_bound, "Y")
Exemplo n.º 2
0
 def __str__(self):
     if self.day:
         return dateformat.format(self.lower_bound, "l jS F Y")
     elif self.month:
         return dateformat.format(self.lower_bound, "F Y")
     else:
         return dateformat.format(self.lower_bound, "Y")
Exemplo n.º 3
0
def diff_date(date, limen=2):
    if not date:
        return _('unknown')

    now = datetime.datetime.now()
    diff = now - date
    days = diff.days
    hours = int(diff.seconds/3600)
    minutes = int(diff.seconds/60)

    if date.year != now.year:
        return dateformat.format(date, 'd M \'y, H:i')
    elif days > 2 or (limen == 0):
        return dateformat.format(date, 'd M, H:i')

    elif days == 2:
        return _('2 days ago')
    elif days == 1:
        return _('yesterday')
    elif minutes >= 60:
        return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours}
    elif diff.seconds >= 60:
        return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes}
    else:
        return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
Exemplo n.º 4
0
def naturaldatetime(value):
    """
    Return given past datetime formatted "naturally", omitting unnecessary data.

    If the given date is today, display only the time. If the date is within
    the past week, prepend the three-letter day of the week name to the
    time. Otherwise, prepend e.g. "Jan 23 2012", omitting the year if it is
    the current year.

    A given timezone-naive datetime is assumed to be in the current timezone.

    """
    if timezone.is_naive(value):
        value = timezone.make_aware(value, timezone.get_current_timezone())
    else:
        value = timezone.localtime(value)
    nowdt = timezone.localtime(now())
    delta = nowdt - value
    period = dateformat.format(value, 'A').lower()
    if delta.days <= 0:
        format_string = 'f'
    elif 0 < delta.days < 7:
        format_string = 'D f'
    elif nowdt.year == value.year:
        format_string = 'M j, f'
    else:
        format_string = 'M j Y, f'

    return dateformat.format(value, format_string) + period
Exemplo n.º 5
0
def export_as_csv(queryset, fields=None, header=None, filename=None, options=None, out=None):
    """
        Exports a queryset as csv from a queryset with the given fields.

    :param queryset: queryset to export
    :param fields: list of fields names to export. None for all fields
    :param header: if True, the exported file will have the first row as column names
    :param filename: name of the filename
    :param options: CSVOptions() instance or none
    :param: out: object that implements File protocol. HttpResponse if None.

    :return: HttpResponse instance
    """
    if out is None:
        if filename is None:
            filename = filename or "%s.csv" % queryset.model._meta.verbose_name_plural.lower().replace(" ", "_")
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;filename="%s"' % filename.encode('us-ascii', 'replace')
    else:
        response = out

    if options is None:
        config = csv_options_default
    else:
        config = csv_options_default.copy()
        config.update(options)

    if fields is None:
        fields = [f.name for f in queryset.model._meta.fields]

    dialect = config.get('dialect', None)
    if dialect is not None:
        writer = csv.writer(response, dialect=dialect)
    else:
        writer = csv.writer(response,
                            escapechar=str(config['escapechar']),
                            delimiter=str(config['delimiter']),
                            quotechar=str(config['quotechar']),
                            quoting=int(config['quoting']))

    if bool(header):
        if isinstance(header, (list, tuple)):
            writer.writerow(header)
        else:
            writer.writerow([f for f in fields])

    for obj in queryset:
        row = []
        for fieldname in fields:
            value = get_field_value(obj, fieldname)
            if isinstance(value, datetime.datetime):
                value = dateformat.format(value, config['datetime_format'])
            elif isinstance(value, datetime.date):
                value = dateformat.format(value, config['date_format'])
            elif isinstance(value, datetime.time):
                value = dateformat.format(value, config['time_format'])
            row.append(smart_str(value))
        writer.writerow(row)

    return response
Exemplo n.º 6
0
 def values(self):
     """
     Returns a list of values for this field for this instance. It's a list
     so we can accomodate many-to-many fields.
     """
     # This import is deliberately inside the function because it causes
     # some settings to be imported, and we don't want to do that at the
     # module level.
     if self.field.rel:
         if isinstance(self.field.rel, models.ManyToOneRel):
             objs = getattr(self.instance.instance, self.field.name)
         elif isinstance(self.field.rel, models.ManyToManyRel): # ManyToManyRel
             return list(getattr(self.instance.instance, self.field.name).all())
     elif self.field.choices:
         objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE)
     elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField):
         if self.raw_value:
             date_format, datetime_format, time_format = get_date_formats()
             if isinstance(self.field, models.DateTimeField):
                 objs = capfirst(dateformat.format(self.raw_value, datetime_format))
             elif isinstance(self.field, models.TimeField):
                 objs = capfirst(dateformat.time_format(self.raw_value, time_format))
             else:
                 objs = capfirst(dateformat.format(self.raw_value, date_format))
         else:
             objs = EMPTY_VALUE
     elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField):
         objs = {True: 'Yes', False: 'No', None: 'Unknown'}[self.raw_value]
     else:
         objs = self.raw_value
     return [objs]
Exemplo n.º 7
0
def prep_date(date):
    import datetime
    if date == "month":
        right_now = datetime.datetime.now()
        thisMonth = datetime.datetime(right_now.year,right_now.month,1)#make a datetime obj for 1st of this month
        delta = datetime.timedelta(seconds=1)    #create a delta of 1 second
        last_day = thisMonth - delta #last day of last month
        if last_day.day < right_now.day:
            final_day = last_day.day
        else:
            final_day=right_now.day
        #all this is to have a valid month span for dates, basicly from a month ago(validated) to now		
        #return str(datetime.date(right_now.year,right_now.month-1,final_day))+','+str(datetime.date(right_now.year,right_now.month,right_now.day))
        sDate = dateformat.format(datetime.date(right_now.year,right_now.month-1,final_day), settings.DATE_FORMAT)
        eDate = dateformat.format(datetime.date(right_now.year,right_now.month,right_now.day), settings.DATE_FORMAT)		
        return str(sDate)+","+str(eDate)
    elif (date == "day") | (date == "yesterday"):
        right_now = datetime.datetime.now()
        yesterday = right_now.day-1
        if yesterday == 0:
            thisMonth = datetime.date(right_now.year,right_now.month,1)#make a datetime obj for 1st of this month
            delta = datetime.timedelta(seconds=1)    #create a delta of 1 second
            last_month = thisMonth - delta #last day of last month
            return str(datetime.date(last_month.year,last_month.month, last_month.day))+","+str(datetime.date(last_month.year,last_month.month, last_month.day))
        else:
            sDate = dateformat.format(datetime.date(right_now.year,right_now.month, yesterday), settings.DATE_FORMAT)
            eDate = dateformat.format(datetime.date(right_now.year,right_now.month, yesterday), settings.DATE_FORMAT)
            return str(sDate)+","+str(eDate)
    try:
        x = str(date.split(","))
    except:
        date = str(date)+","+str(date)
    return str(date)
Exemplo n.º 8
0
def last_message(request):
    lastModif = request.GET.get('timestamp')
    
    if Messages.objects.all() :
        currentModif = format(Messages.objects.order_by('-date')[0].date, 'U')
    else:
        currentModif = 0
    
    if  lastModif == "0":
        lastModif = currentModif
    
    while currentModif <= lastModif:
        time.sleep(0.1)
        
        if Messages.objects.all() :
            currentModif = format(Messages.objects.order_by('-date')[0].date, 'U')
        else:
            currentModif = 0
  
    return render(request, 'submissions/message.html',
    {
        'message' : Messages.objects.last(),
        'user' : request.user.profil,
        'timestamp': currentModif
    })
Exemplo n.º 9
0
  def __init__(self, data, survey, record_model, idx=0, description=''):
    """Creates a new SurveyRecordList template.

    Args:
      data: The RequestData object to use.
      survey: The Survey to show the records for
      record_model: The Model class of the Record entities.
      idx: The index of the list to use.
      description: The (optional) description of the list.
    """
    super(SurveyRecordList, self).__init__(data)

    self.survey = survey
    self.record_model = record_model
    self.idx = idx
    self.description = description

    # Create the configuration based on the schema of the survey
    list_config = lists.ListConfiguration()
    schema = surveys.SurveySchema(survey)

    for field in schema:
      label = field.getLabel()
      field_id = field.getFieldName()
      list_config.addColumn(
          field_id, label, field_or_empty(field_id), hidden=True)

    list_config.addColumn(
        'created', 'Created On',
        lambda ent, *args: format(ent.created, DATETIME_FORMAT))
    list_config.addColumn(
        'modified', 'Last Modified On',
        lambda ent, *args: format(ent.modified, DATETIME_FORMAT))
    self.list_config = list_config
Exemplo n.º 10
0
 def value_list(self):
     """
     Returns a list of {value, url} dictionaries representing each value for
     this attribute.
     """
     from django.utils.dateformat import format, time_format
     urls = [None]
     descriptions = [None]
     if self.is_filter:
         if self.is_lookup:
             urls = [look and '/%s/by-%s/%s/' % (self.schema_slug, self.sf.slug, look.slug) or None for look in self.values]
         elif isinstance(self.raw_value, datetime.date):
             urls = ['/%s/by-%s/%s/%s/%s/' % (self.schema_slug, self.sf.slug, self.raw_value.year, self.raw_value.month, self.raw_value.day)]
         elif self.raw_value in (True, False, None):
             urls = ['/%s/by-%s/%s/' % (self.schema_slug, self.sf.slug, {True: 'yes', False: 'no', None: 'na'}[self.raw_value])]
     if self.is_lookup:
         values = [val and val.name or 'None' for val in self.values]
         descriptions = [val and val.description or None for val in self.values]
     elif isinstance(self.raw_value, datetime.datetime):
         values = [format(self.raw_value, 'F j, Y, P')]
     elif isinstance(self.raw_value, datetime.date):
         values = [format(self.raw_value, 'F j, Y')]
     elif isinstance(self.raw_value, datetime.time):
         values = [time_format(self.raw_value, 'P')]
     elif self.raw_value is True:
         values = ['Yes']
     elif self.raw_value is False:
         values = ['No']
     elif self.raw_value is None:
         values = ['N/A']
     else:
         values = [self.raw_value]
     return [{'value': value, 'url': url, 'description': description} for value, url, description in zip(values, urls, descriptions)]
Exemplo n.º 11
0
def repdate (approx):
    """Alternative to Django's date filter which doesn't play well with ApproximateDateFields.

    @param approx: approximate date
    @type: ApproximateDateField
    @return: nicely formatted date
    @rtype: str
    """
    if not approx:
        return ''

    if approx.month == 1 and approx.day == 1:
        return dateformat.format(approx, 'Y').encode('utf-8')
    elif hasattr(approx, 'future') and approx.future:
        return _(u'future')
    elif approx.year and approx.month and approx.day:
        # return dateformat.format(approx, 'j F Y').encode('utf-8')
        return dateformat.format(approx, 'Y').encode('utf-8')
    elif approx.year and approx.month:
        #return dateformat.format(approx, 'F Y').encode('utf-8')
        return dateformat.format(approx, 'Y').encode('utf-8')
    elif approx.year:
        return dateformat.format(approx, 'Y').encode('utf-8')
    else:
        return _(u'invalid')
Exemplo n.º 12
0
    def render(self, context):
        try:
            start_date = self.start_date.resolve(context)
            end_date = self.end_date.resolve(context)
        except template.VariableDoesNotExist:
            return ''
        
        start_format = ""
        end_format = ""

        if end_date:
            if end_date and start_date == end_date :
                start_format = "%s %s, %s" % (self.format['month'], self.format['day'], self.format['year'])
            else :
                start_format = "%s %s" % (self.format['month'], self.format['day'])
                end_format = "%s %s, %s" % (self.format['month'], self.format['day'], self.format['year'])

                if start_date.year != end_date.year:
                    start_format += ", %s" % self.format['year']
        else:
            start_format = "%s %s, %s" % (self.format['month'], self.format['day'], self.format['year'])
                
        ret = dateformat.format(start_date, start_format)
        if end_format:
            ret += " - " + dateformat.format(end_date, end_format)
        return ret
Exemplo n.º 13
0
def ajax_allocation_details(request):
    if request.is_ajax():
        aloc = Allocation.objects.get(id=int(request.POST['id']))
        html ='''<table class="TFtable-lists"><tr><td><p class='my-modal-content'>Book Code : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>Book Title : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>Allocated To : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>Start Date : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>End Date : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>Allocated By : </td><td>
			<span>%s</span></p></td></tr><tr><td>
			<p class='my-modal-content'>Status : </td><td>
		        <span >%s</span></p></td></tr></table>
        ''' % (aloc.book.code,
               aloc.book.title,
               aloc.student,
               dateformat.format(aloc.start_date, 'F j, Y'),
               dateformat.format(aloc.end_date, 'F j, Y'),
               aloc.allocated_by,
               bookFlags.get(aloc.status,'Undefined'))
        return HttpResponse(html)
Exemplo n.º 14
0
    def test_changes_display_dict_datetime(self):
        timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc)
        date = datetime.date(2017, 1, 10)
        time = datetime.time(12, 0)
        dtm = DateTimeFieldModel(label='DateTimeField model', timestamp=timestamp, date=date, time=time, naive_dt=self.now)
        dtm.save()
        localized_timestamp = timestamp.astimezone(gettz(settings.TIME_ZONE))
        self.assertTrue(dtm.history.latest().changes_display_dict["timestamp"][1] == \
                        dateformat.format(localized_timestamp, settings.DATETIME_FORMAT),
                        msg=("The datetime should be formatted according to Django's settings for"
                             " DATETIME_FORMAT"))
        timestamp = timezone.now()
        dtm.timestamp = timestamp
        dtm.save()
        localized_timestamp = timestamp.astimezone(gettz(settings.TIME_ZONE))
        self.assertTrue(dtm.history.latest().changes_display_dict["timestamp"][1] == \
                        dateformat.format(localized_timestamp, settings.DATETIME_FORMAT),
                        msg=("The datetime should be formatted according to Django's settings for"
                             " DATETIME_FORMAT"))

        # Change USE_L10N = True
        with self.settings(USE_L10N=True, LANGUAGE_CODE='en-GB'):
            self.assertTrue(dtm.history.latest().changes_display_dict["timestamp"][1] == \
                        formats.localize(localized_timestamp),
                        msg=("The datetime should be formatted according to Django's settings for"
                             " USE_L10N is True with a different LANGUAGE_CODE."))
Exemplo n.º 15
0
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateField) or isinstance(field, models.TimeField):
        if value:
            date_format = formats.get_format('DATE_FORMAT')
            datetime_format = formats.get_format('DATETIME_FORMAT')
            time_format = formats.get_format('TIME_FORMAT')
            if isinstance(field, models.DateTimeField):
                return capfirst(dateformat.format(value, datetime_format))
            elif isinstance(field, models.TimeField):
                return capfirst(dateformat.time_format(value, time_format))
            else:
                return capfirst(dateformat.format(value, date_format))
        else:
            return EMPTY_CHANGELIST_VALUE

    elif isinstance(field, models.DecimalField):
        if value is not None:
            return ('%%.%sf' % field.decimal_places) % value
        else:
            return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.FloatField):
        return escape(value)
    else:
        return smart_str(value)
Exemplo n.º 16
0
    def _render_obj_list(self, obj, fields):
        """
        methodo usado para rendererizar um objeto nao suportado pelo simplejson
        parametros
        obj: é o objeto em si
        list_fields: os atributos desse objeto que serão renderizados
        a diferença do anterior que tudo vai ser realizado em forma de lista
        """

        list_obj = []

        for field in fields:
            attr, attrfound = self._find_attr(obj, field)

            if not attrfound:
                list_obj.append(None)
                continue

            if callable(attr):
                attr = attr()

            if isinstance(attr, datetime.datetime):
                attr = format(attr, DATETIME_FORMAT)

            if isinstance(attr, datetime.date):
                attr = format(attr, DATE_FORMAT)

            if hasattr(attr, "__unicode__"):
                attr = unicode(attr)

            list_obj.append(attr)

        return list_obj
Exemplo n.º 17
0
  def safe(self, value):
    """Returns the safe representation of the specified value. It is assumed
    that only date values are passed here, so the the output is not HTML
    escaped.

    Args:
      value: the specified string or a date for which
          to return the safe representation

    Returns:
      textual representation of the specified value or the empty string for
      None and the empty string.

    Raises:
      ValueError: if the specified value is invalid
      TypeError: if the specified value is neither a number nor a string
    """
    if not value:
      return 'N/A'
    elif self.birthdate:
      return dateformat.format(value, BIRTHDATE_FORMAT)
    elif isinstance(value, datetime.datetime):
      return dateformat.format(value, DATETIME_FORMAT)
    else:
      return dateformat.format(value, DATE_FORMAT)
Exemplo n.º 18
0
    def __init__(self, request, data, survey):
        """Initializes the component.

    Args:
      request: The HTTPRequest object
      data: The RequestData object
      survey: the OrgApplicationSurvey entity
    """
        super(MyOrgApplicationsComponent, self).__init__(request, data)

        # passed in so we don't have to do double queries
        self.survey = survey

        list_config = lists.ListConfiguration()

        list_config.addSimpleColumn("name", "Name")
        list_config.addSimpleColumn("org_id", "Organization ID")
        list_config.addColumn("created", "Created On", lambda ent, *args: format(ent.created, DATETIME_FORMAT))
        list_config.addColumn("modified", "Last Modified On", lambda ent, *args: format(ent.modified, DATETIME_FORMAT))

        if self.data.timeline.surveyPeriod(survey):
            url_name = "gci_retake_org_app"
        else:
            url_name = "gci_show_org_app"

        list_config.setRowAction(lambda e, *args: data.redirect.id(e.key().id()).urlOf(url_name))

        self._list_config = list_config

        super(MyOrgApplicationsComponent, self).__init__(request, data)
Exemplo n.º 19
0
    def save(self, old_record, list_record, detail_record):
        if old_record is not None:
            # Street closures never change, so we don't have to
            # worry about changing applications that already exist.
            self.logger.debug('Closure already exists')
            return

        closure_type = self.get_or_create_lookup('closure_type', capfirst(list_record['closure_type'].lower()), list_record['closure_type'].upper())

        # Calculate a "friendly" date range to avoid lameness like "from Oct. 3 to Oct. 3".
        if list_record['start_date'] == list_record['end_date']:
            friendly_date_range = 'on %s' % format(list_record['start_date'], 'F j')
        else:
            friendly_date_range = 'from %s to %s' % (format(list_record['start_date'], 'F j'), format(list_record['end_date'], 'F j'))

        attributes = {
            'block_from': list_record['block_from'],
            'block_to': list_record['block_to'],
            'address': list_record['address'],
            'street_dir': list_record['street_dir'],
            'street_name': list_record['street_name'],
            'street_suffix': list_record['street_suffix'],
            'closure_type': closure_type.id,
            'end_date': list_record['end_date'],
            'details': list_record['details'],
            'date_posted': list_record['date_posted'],
        }
        self.create_newsitem(
            attributes,
            title=u'%s %s' % (closure_type.name, friendly_date_range),
            url=SOURCE_URL,
            pub_date=list_record['date_posted'],
            item_date=list_record['start_date'],
            location_name=list_record['address'],
        )
Exemplo n.º 20
0
    def serialize(self, dt_format=None, zone=None):
        """
        Serializes datetimes using given format or default format if None,
        in given or original time zone
        Returns formatted strings as dict for both datetime fields if present

        TimeWarp class now has built in time formats
        Serializer can use given format or you can choose from built in formats
        Builtin formats use Django's date formatter and argument format uses Python's own
        Also, datetimes are cast to given time zone or the
        original_timezone is used

        :param dt_format: a key in class formats or a Python format string
        :type dt_format: string
        :return: a dict with object's used datetime fields formatted
        :rtype: dict[string, string]
        """
        if not zone:
            zone = self.original_timezone
        else:
            zone = pytz.timezone(zone)
        resp = {}
        for key in ("dt", "end_dt"):
            field = getattr(self, key)
            if field:
                field = field.astimezone(zone)
                if not dt_format:
                    resp[key] = format(field, self.SERIALIZATION_FORMATS["finnish"])
                else:
                    try:
                        resp[key] = format(field, self.SERIALIZATION_FORMATS[dt_format])
                    except KeyError:
                        resp[key] = dt_format.format(field)
        return resp
Exemplo n.º 21
0
 def _format(self, value, label, cast=None, null='(None)', empty='(Empty)', places=2, map=None, max_length=100, truncate='...'):
     """Intelligently format typed data"""
     if value is None:
         value = null % {'label': label}
     if cast is not None:
         value = cast(value)
 
     if isinstance(value, (datetime.datetime, datetime.time, datetime.date)):
         if isinstance(value, datetime.datetime):
             result_repr = capfirst(dateformat.format(value, settings.DATE_FORMAT))
         elif isinstance(value, datetime.time):
             result_repr = capfirst(dateformat.time_format(value, settings.TIME_FORMAT))
         else:
             result_repr = capfirst(dateformat.format(value, settings.DATE_FORMAT))
     elif isinstance(value, bool):
         BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
         result_repr = E.IMG(src="%sadmin/img/icon-%s.gif" % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[value]), alt="%s" % value)
     elif isinstance(value, (float, Decimal)):
         result_repr = (u'%%.%sf' % places) % value
     elif map:
         result_repr = map.get(value, '--')
     elif isinstance(value, (SafeUnicode, SafeString)):
         try:
             return etree.fromstring(value)
         except etree.XMLSyntaxError:
             result_repr = value
     else:
         result_repr = unicode(value)
     
     if empty and result_repr == '':
         result_repr = empty % {'label': label} 
     
     if not isinstance(result_repr, (SafeUnicode, SafeString)) and max_length and len(result_repr) > max_length:
         result_repr = E.ABBR(result_repr[:max_length-len(truncate)] + truncate, title=result_repr)
     return result_repr
Exemplo n.º 22
0
	def get_context_data(self, **kwargs):
		context = super(IndexJsonView, self).get_context_data(**kwargs)
		stories = context['stories']
		context = self.clean_context(context)
		context['stories'] = []
		for story in stories:
			story_json = {
				'id': story.id,
				'title': story.title,
				'selfpost': story.selfpost,
				'poll': story.poll,
				'username': story.username,
				'score': story.score,
				'comments': story.comments,
				'story_type': story.story_type,
				'time': format(story.time, 'r'),
				'time_unix': format(story.time, 'U'),
				'cache': format(story.cache, 'r'),
				'cache_unix': format(story.cache, 'U')
			}
			if not story.selfpost:
				story_json['url'] = story.url
				story_json['domain'] = domain(story.url)
			context['stories'].append(story_json)
		context['page'] = {'current': stories.number, 'total': stories.paginator.num_pages}
		return context
Exemplo n.º 23
0
    def _create_date_range_label(self, start, end):
        """ Create a label to display a date range.

        The dates are formatter such that:
        - If either start or end include hours/minutes/seconds
          that are not 00:00:00 then the full date time is
          displayed;
        - If both start and end have zero hours/minutes/seconds
          then only the day is displayed, and the end day
          is set to the previous day (to show an inclusive
          range);

        Args:
            start (datetime): Start date time
            end (datetime): End date time
        Returns:
            str: Label to use for the date range.
        """
        if not start.time() and not end.time():
            start_str = dateformat.format(start,
                                          settings.SHORT_DATE_FORMAT)
            end_str = dateformat.format(end - timedelta(days=1),
                                        settings.SHORT_DATE_FORMAT)
        else:
            start_str = dateformat.format(start,
                                          settings.SHORT_DATETIME_FORMAT),
            end_str = dateformat.format(end,
                                        settings.SHORT_DATETIME_FORMAT)
        if start_str == end_str:
            return _('%(date)s') % {'date': start_str}
        else:
            return _('%(start)s - %(end)s') % {
                'start': start_str,
                'end': end_str
            }
Exemplo n.º 24
0
def iso_time_tag(date):
    return {
        'timestamp': format(date, 'c'),
        'month': format(date, 'm'),
        'day': format(date, 'd'),
        'year': format(date, 'Y'),
    }
Exemplo n.º 25
0
def report_date_hierarchy(cl):
    if cl.date_hierarchy:
        model, field_name = get_date_model_field(cl.model, cl.date_hierarchy)
        rel_query_set = model.objects.all()

        year_field = "%s__year" % cl.date_hierarchy
        month_field = "%s__month" % cl.date_hierarchy
        day_field = "%s__day" % cl.date_hierarchy
        field_generic = "%s__" % cl.date_hierarchy
        year_lookup = cl.params.get(year_field)
        month_lookup = cl.params.get(month_field)
        day_lookup = cl.params.get(day_field)
        year_month_format, month_day_format = get_partial_date_formats()

        link = lambda d: mark_safe(cl.get_query_string(d, [field_generic]))

        if year_lookup and month_lookup and day_lookup:
            day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
            return {
                "show": True,
                "back": {
                    "link": link({year_field: year_lookup, month_field: month_lookup}),
                    "title": dateformat.format(day, year_month_format),
                },
                "choices": [{"title": dateformat.format(day, month_day_format)}],
            }
        elif year_lookup and month_lookup:
            days = rel_query_set.filter(
                **{"%s__year" % field_name: year_lookup, "%s__month" % field_name: month_lookup}
            ).dates(field_name, "day")
            return {
                "show": True,
                "back": {"link": link({year_field: year_lookup}), "title": year_lookup},
                "choices": [
                    {
                        "link": link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
                        "title": dateformat.format(day, month_day_format),
                    }
                    for day in days
                ],
            }
        elif year_lookup:
            months = rel_query_set.filter(**{"%s__year" % field_name: year_lookup}).dates(field_name, "month")
            return {
                "show": True,
                "back": {"link": link({}), "title": _("All dates")},
                "choices": [
                    {
                        "link": link({year_field: year_lookup, month_field: month.month}),
                        "title": dateformat.format(month, year_month_format),
                    }
                    for month in months
                ],
            }
        else:
            years = rel_query_set.dates(field_name, "year")
            return {
                "show": True,
                "choices": [{"link": link({year_field: year.year}), "title": year.year} for year in years],
            }
Exemplo n.º 26
0
def get_archive():    
    categories = []
    tags = []
    archive = []
    entries = Entry.objects.filter(status__exact = 'publish').order_by('-pub_date')
    months = entries.dates('pub_date','month',order='DESC')
    for mon in months:
        m = Archive()
        m.link = "/archive/" + format(mon,'Y/m') + "/"
        m.title = format(mon,'b,Y')
        archive.append(m)
    for entry in entries:
        if entry.category not in categories:
            categories.append(entry.category)    
        t = entry.tags.all()
        for tag in t:
            if tag not in tags:
                tags.append(tag)  
    if tags:
        min_count = max_count = tags[0].count
        for tag in tags:
            if tag.count < min_count:
                min_count = tag.count
            if max_count < tag.count:
                max_count = tag.count
        range = float(max_count - min_count)
        if range == 0.0:
            range = 1.0
        for tag in tags:
            tag.weight = int(MAX_WEIGHT * (tag.count - min_count) / range)    
    return {'entries':entries,'categories':categories,'tags':tags,'archive':archive}
Exemplo n.º 27
0
def smart_date(start_date=None, end_date=None, date_format='j.n.'):
    from datetime import datetime
    from django.utils import dateformat

    now = datetime.now()

    components = []

    if start_date:
        components.append(dateformat.format(start_date, date_format))
        if start_date.year != now.year: components.append(str(start_date.year))
        
        start_time = start_date.time()
        if start_time.hour > 0 or start_time.minute > 0:
            components.append(dateformat.time_format(start_time,r',&\n\b\s\p;G:i'))

    if end_date:
        components.append(' &ndash; ')
        if (not start_date) or end_date.date() != start_date.date():
            components.append(dateformat.format(end_date, date_format))
            if end_date.year != now.year: components.append(str(end_date.year))

        end_time = end_date.time()
        if end_time.hour > 0 or end_time.minute > 0:
            components.append(dateformat.time_format(end_time,r',&\n\b\s\p;G:i'))
    
    return ''.join(components)
Exemplo n.º 28
0
 def __init__(self, user):
     
     self.s_date = format(datetime.date.today(), 'Y-m-d')
     self.f_date = format(datetime.date.today(), 'l, M d, Y')
     
     self.user = user
 
     self.flights = Flight.objects\
                          .user(user)\
                          .order_by('date')\
                          .select_related()
                          
     cd = 'attachment; filename=logbook{0}.pdf'.format(self.s_date)
     self.response = HttpResponse(mimetype='application/pdf')
     self.response['Content-Disposition'] = cd
     
     self.doc = SimpleDocTemplate(self.response,
                                  pagesize=landscape(letter), 
                                  showBoundary=1,
                                  leftMargin=inch/4,
                                  rightMargin=inch/4,
                                  topMargin=inch/4,
                                  bottomMargin=inch/4,
                                  title="FlightLogg.in Logbook",
                                  author="FlightLogg.in")
Exemplo n.º 29
0
def generate_image_filename(instance, filename):
    if instance.cjr_id is None and instance.is_cal_image:
        cjr_id = 0

    elif instance.cjr is None and not instance.is_cal_image:
        raise Exception("The CJR must be set on non-calibration images before setting the image " +
                        "so that the filename can be generated.")
    else:
        cjr_id = instance.cjr.id

    if not all([bool(x) for x in (instance, instance.xp_id, instance.capture_timestamp)]):
        raise Exception("The xp and capture_timestamp must be set before setting the image " +
                        "so that the filename can be generated.")
    utc_ts = round(float(dud.format(instance.capture_timestamp, 'U.u')), 2)
    temp_dt = datetime.datetime.utcfromtimestamp(utc_ts).replace(tzinfo=dut.utc)

    return (
        u'experiment_imagery/stills/{dtg}'.format(
            dtg=dud.format(instance.capture_timestamp, 'Y.m.d')
        ) +
        u'/XP-{instance.xp_id}_CJR-{cjr_id}_{instance.xp.species.shortname}_'.format(
            instance=instance,
            cjr_id=cjr_id
        ) +
        u'{file_dtg}_{file_ts}.jpg'.format(
            file_dtg=temp_dt.astimezone(dut.LocalTimezone()).strftime(
                settings.FILENAME_DATE_FORMAT),
            file_ts=utc_ts
        )
    )
Exemplo n.º 30
0
def date_hierarchy(cl):
    if cl.lookup_opts.admin.date_hierarchy:
        field_name = cl.lookup_opts.admin.date_hierarchy
        year_field = '%s__year' % field_name
        month_field = '%s__month' % field_name
        day_field = '%s__day' % field_name
        field_generic = '%s__' % field_name
        year_lookup = cl.params.get(year_field)
        month_lookup = cl.params.get(month_field)
        day_lookup = cl.params.get(day_field)
        year_month_format, month_day_format = get_partial_date_formats()

        link = lambda d: cl.get_query_string(d, [field_generic])

        if year_lookup and month_lookup and day_lookup:
            day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup, month_field: month_lookup}),
                    'title': dateformat.format(day, year_month_format)
                },
                'choices': [{'title': dateformat.format(day, month_day_format)}]
            }
        elif year_lookup and month_lookup:
            days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day')
            return {
                'show': True,
                'back': {
                    'link': link({year_field: year_lookup}),
                    'title': year_lookup
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
                    'title': dateformat.format(day, month_day_format)
                } for day in days]
            }
        elif year_lookup:
            months = cl.query_set.filter(**{year_field: year_lookup}).dates(field_name, 'month')
            return {
                'show' : True,
                'back': {
                    'link' : link({}),
                    'title': _('All dates')
                },
                'choices': [{
                    'link': link({year_field: year_lookup, month_field: month.month}),
                    'title': dateformat.format(month, year_month_format)
                } for month in months]
            }
        else:
            years = cl.query_set.dates(field_name, 'year')
            return {
                'show': True,
                'choices': [{
                    'link': link({year_field: year.year}),
                    'title': year.year
                } for year in years]
            }
Exemplo n.º 31
0
def datetime_to_unix(datetime_):
    return int(dateformat.format(datetime_, "U"))
Exemplo n.º 32
0
 def unix_time(self):
     return format(self.created_on, 'U')
Exemplo n.º 33
0
 def get_timeuntil(self, obj):
     fmt = get_format('DATETIME_FORMAT')
     next_run = obj.next_run or timezone.now()
     value = capfirst(dateformat.format(utils.localtime(next_run), fmt))
     return mark_safe("%s<br /><span class='mini'>(%s)</span>" %
                      (value, obj.get_timeuntil()))
Exemplo n.º 34
0
 def _get_pretty_published_date(self, datetime_string):
     dt = parse_datetime(datetime_string)
     return dateformat.format(dt, 'd E Y г.')
Exemplo n.º 35
0
 def test_futuredates(self):
     the_future = datetime.datetime(2100, 10, 25, 0, 00)
     self.assertEquals(dateformat.format(the_future, r'Y'), u'2100')
Exemplo n.º 36
0
    def test_am_pm(self):
        my_birthday = datetime.datetime(1979, 7, 8, 22, 00)

        self.assertEquals(dateformat.format(my_birthday, 'a'), u'p.m.')
Exemplo n.º 37
0
    def test_empty_format(self):
        my_birthday = datetime.datetime(1979, 7, 8, 22, 00)

        self.assertEquals(dateformat.format(my_birthday, ''), u'')
Exemplo n.º 38
0
    def save(self, force_retrieve=False, *args, **kwargs):
        """
        Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe

        API or update the local object with data fetched from Stripe.
        """
        stripe.api_key = stripe_settings.API_KEY
        if self._previous_is_deleted != self.is_deleted and self.is_deleted:
            try:
                stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
                # make sure to delete correct coupon
                if self.created == timestamp_to_timezone_aware_date(
                        stripe_coupon["created"]):
                    stripe_coupon.delete()
            except stripe.error.InvalidRequestError:
                # means that the coupon has already been removed from stripe
                pass

            return super(StripeCoupon, self).save(*args, **kwargs)

        if self.pk or force_retrieve:
            try:
                stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
                if not force_retrieve:
                    stripe_coupon.metadata = self.metadata
                    stripe_coupon.save()

                if force_retrieve:
                    # make sure we are not creating a duplicate
                    coupon_qs = StripeCoupon.objects.filter(
                        coupon_id=self.coupon_id)
                    if coupon_qs.filter(
                            created=timestamp_to_timezone_aware_date(
                                stripe_coupon["created"])).exists():
                        raise StripeCouponAlreadyExists

                    # all old coupons should be deleted
                    for coupon in coupon_qs:
                        coupon.is_deleted = True
                        super(StripeCoupon, coupon).save(
                        )  # use super save() to call pre/post save signals
                # update all fields in the local object in case someone tried to change them
                self.update_from_stripe_data(
                    stripe_coupon,
                    exclude_fields=["metadata"] if not force_retrieve else [])
                self.stripe_response = stripe_coupon
            except stripe.error.InvalidRequestError:
                if force_retrieve:
                    raise

                self.is_deleted = True
        else:
            self.stripe_response = stripe.Coupon.create(
                id=self.coupon_id,
                duration=self.duration,
                amount_off=int(self.amount_off *
                               100) if self.amount_off else None,
                currency=self.currency,
                duration_in_months=self.duration_in_months,
                max_redemptions=self.max_redemptions,
                metadata=self.metadata,
                percent_off=self.percent_off,
                redeem_by=int(dateformat.format(self.redeem_by, "U"))
                if self.redeem_by else None,
            )
            # stripe will generate coupon_id if none was specified in the request
            if not self.coupon_id:
                self.coupon_id = self.stripe_response["id"]

        self.created = timestamp_to_timezone_aware_date(
            self.stripe_response["created"])
        # for future
        self.is_created_at_stripe = True
        return super(StripeCoupon, self).save(*args, **kwargs)
Exemplo n.º 39
0
 def __str__(self):
     return "notification: " + self.content + "(" + format(
         self.modified_at, 'U') + ")"
Exemplo n.º 40
0

def referenced_case_attribute(case, field_name):
    if not case.indices[0]['referenced_id']:
        return ""
    referenced_case = CommCareCase.get(case.indices[0]['referenced_id'])
    if hasattr(referenced_case, field_name):
        return getattr(referenced_case, field_name)
    else:
        return ""


def get_datepart(case, t='n'):
    child_date_of_death = case.get_case_property('child_date_of_death')
    if child_date_of_death:
        return format(force_to_datetime(child_date_of_death), t)
    else:
        return ""


def calculate_weight(case):
    weight_birth = case.get_case_property('weight_birth')
    if weight_birth:
        #Probably measured in grams. Should be converted to kilograms
        if float(weight_birth) > 10:
            return str(float(weight_birth) / 1000.0)
        else:
            return weight_birth
    return ""

Exemplo n.º 41
0
def items_for_result(cl, result):
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = ''
        try:
            f = cl.lookup_opts.get_field(field_name)
        except models.FieldDoesNotExist:
            # For non-field list_display values, the value is either a method
            # or a property.
            try:
                attr = getattr(result, field_name)
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if isinstance(attr, collections.Callable):
                    attr = attr()
                if boolean:
                    allow_tags = True
                    result_repr = _boolean_icon(attr)
                else:
                    result_repr = smart_unicode(attr)
            except (AttributeError, ObjectDoesNotExist):
                result_repr = EMPTY_CHANGELIST_VALUE
            else:
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if not allow_tags:
                    result_repr = escape(result_repr)
                else:
                    result_repr = mark_safe(result_repr)
        else:
            field_val = getattr(result, f.attname)

            if isinstance(f.rel, models.ManyToOneRel):
                if field_val is not None:
                    result_repr = escape(getattr(result, f.name))
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
            # Dates and times are special: They're formatted in a certain way.
            elif isinstance(f, models.DateField) or isinstance(
                    f, models.TimeField):
                if field_val:
                    (date_format, datetime_format,
                     time_format) = get_date_formats()
                    if isinstance(f, models.DateTimeField):
                        result_repr = capfirst(
                            dateformat.format(field_val, datetime_format))
                    elif isinstance(f, models.TimeField):
                        result_repr = capfirst(
                            dateformat.time_format(field_val, time_format))
                    else:
                        result_repr = capfirst(
                            dateformat.format(field_val, date_format))
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
                row_class = ' class="nowrap"'
            # Booleans are special: We use images.
            elif isinstance(f, models.BooleanField) or isinstance(
                    f, models.NullBooleanField):
                result_repr = _boolean_icon(field_val)
            # DecimalFields are special: Zero-pad the decimals.
            elif isinstance(f, models.DecimalField):
                if field_val is not None:
                    result_repr = ('%%.%sf' % f.decimal_places) % field_val
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
            # Fields with choices are special: Use the representation
            # of the choice.
            elif f.choices:
                result_repr = dict(f.choices).get(field_val,
                                                  EMPTY_CHANGELIST_VALUE)
            else:
                result_repr = escape(field_val)
        if force_unicode(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links
            ) or field_name in cl.list_display_links:
            table_tag = {True: 'th', False: 'td'}[first]
            first = False
            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            result_id = repr(force_unicode(getattr(result, pk)))[1:]
            yield mark_safe('<%s%s><a href="%s"%s>%s</a></%s>' % \
                (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
        else:
            yield mark_safe('<td%s>%s</td>' %
                            (row_class, conditional_escape(result_repr)))
Exemplo n.º 42
0
def date_hierarchy(cl):
    if cl.date_hierarchy:
        field_name = cl.date_hierarchy
        year_field = '%s__year' % field_name
        month_field = '%s__month' % field_name
        day_field = '%s__day' % field_name
        field_generic = '%s__' % field_name
        year_lookup = cl.params.get(year_field)
        month_lookup = cl.params.get(month_field)
        day_lookup = cl.params.get(day_field)
        year_month_format, month_day_format = get_partial_date_formats()

        link = lambda d: mark_safe(cl.get_query_string(d, [field_generic]))

        if year_lookup and month_lookup and day_lookup:
            day = datetime.date(int(year_lookup), int(month_lookup),
                                int(day_lookup))
            return {
                'show': True,
                'back': {
                    'link':
                    link({
                        year_field: year_lookup,
                        month_field: month_lookup
                    }),
                    'title':
                    dateformat.format(day, year_month_format)
                },
                'choices': [{
                    'title': dateformat.format(day, month_day_format)
                }]
            }
        elif year_lookup and month_lookup:
            days = cl.query_set.filter(**{
                year_field: year_lookup,
                month_field: month_lookup
            }).dates(field_name, 'day')
            return {
                'show':
                True,
                'back': {
                    'link': link({year_field: year_lookup}),
                    'title': year_lookup
                },
                'choices': [{
                    'link':
                    link({
                        year_field: year_lookup,
                        month_field: month_lookup,
                        day_field: day.day
                    }),
                    'title':
                    dateformat.format(day, month_day_format)
                } for day in days]
            }
        elif year_lookup:
            months = cl.query_set.filter(**{
                year_field: year_lookup
            }).dates(field_name, 'month')
            return {
                'show':
                True,
                'back': {
                    'link': link({}),
                    'title': _('All dates')
                },
                'choices': [{
                    'link':
                    link({
                        year_field: year_lookup,
                        month_field: month.month
                    }),
                    'title':
                    dateformat.format(month, year_month_format)
                } for month in months]
            }
        else:
            years = cl.query_set.dates(field_name, 'year')
            return {
                'show':
                True,
                'choices': [{
                    'link': link({year_field: year.year}),
                    'title': year.year
                } for year in years]
            }
Exemplo n.º 43
0
 def f_get_date_time_format(str_format):
     return dateformat.format(CommonUtil().f_get_date_time(), str_format)
Exemplo n.º 44
0
def csv_date(dt):
    return dateformat.format(timezone.make_naive(dt), DATETIME_FORMAT)
Exemplo n.º 45
0
def items_for_result(cl, result, form):
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = ''
        try:
            f = cl.lookup_opts.get_field(field_name)
        except models.FieldDoesNotExist:
            # For non-field list_display values, the value is either a method,
            # property or returned via a callable.
            try:
                if callable(field_name):
                    attr = field_name
                    value = attr(result)
                elif hasattr(cl.model_admin, field_name) and \
                   not field_name == '__str__' and not field_name == '__unicode__':
                    attr = getattr(cl.model_admin, field_name)
                    value = attr(result)
                else:
                    attr = getattr(result, field_name)
                    if callable(attr):
                        value = attr()
                    else:
                        value = attr
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_unicode(value)
            except (AttributeError, ObjectDoesNotExist):
                result_repr = EMPTY_CHANGELIST_VALUE
            else:
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if not allow_tags:
                    result_repr = escape(result_repr)
                else:
                    result_repr = mark_safe(result_repr)
        else:
            field_val = getattr(result, f.attname)

            if isinstance(f.rel, models.ManyToOneRel):
                if field_val is not None:
                    result_repr = escape(getattr(result, f.name))
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
            # Dates and times are special: They're formatted in a certain way.
            elif isinstance(f, models.DateField) or isinstance(
                    f, models.TimeField):
                if field_val:
                    (date_format, datetime_format,
                     time_format) = get_date_formats()
                    if isinstance(f, models.DateTimeField):
                        result_repr = capfirst(
                            dateformat.format(field_val, datetime_format))
                    elif isinstance(f, models.TimeField):
                        result_repr = capfirst(
                            dateformat.time_format(field_val, time_format))
                    else:
                        result_repr = capfirst(
                            dateformat.format(field_val, date_format))
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
                row_class = ' class="nowrap"'
            # Booleans are special: We use images.
            elif isinstance(f, models.BooleanField) or isinstance(
                    f, models.NullBooleanField):
                result_repr = _boolean_icon(field_val)
            # DecimalFields are special: Zero-pad the decimals.
            elif isinstance(f, models.DecimalField):
                if field_val is not None:
                    result_repr = ('%%.%sf' % f.decimal_places) % field_val
                else:
                    result_repr = EMPTY_CHANGELIST_VALUE
            # Fields with choices are special: Use the representation
            # of the choice.
            elif f.choices:
                result_repr = dict(f.choices).get(field_val,
                                                  EMPTY_CHANGELIST_VALUE)
            else:
                result_repr = escape(field_val)
        if force_unicode(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links
            ) or field_name in cl.list_display_links:
            table_tag = {True: 'th', False: 'td'}[first]
            first = False
            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = repr(force_unicode(value))[1:]
            yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \
                (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if form and field_name in form.fields:
                bf = form[field_name]
                result_repr = mark_safe(
                    force_unicode(bf.errors) + force_unicode(bf))
            else:
                result_repr = conditional_escape(result_repr)
            yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))
    if form:
        yield mark_safe(force_unicode(form[cl.model._meta.pk.attname]))
Exemplo n.º 46
0
def challenge_new(request):

    if request.method == 'POST':
        form = ChallengeForm(request.POST, request.FILES)
        if form.is_valid():
            #No validation here (should already be done .is_valid)

            #need to save to assign id
            new_challenge = form.save()

            #parse dockerfile for list of ports
            if new_challenge.upload:
                if new_challenge.hosted:

                    try:
                        ports = list()
                        for line in new_challenge.upload.file:
                            line = line.decode('utf-8')
                            start = 'EXPOSE '

                            if (start in line):
                                possible_port = (line[line.find(start) +
                                                      len(start):])
                                ports.append(possible_port.split())

                        # flatten list
                        flattened_ports = list(
                            set([val for sublist in ports for val in sublist]))
                        print(flattened_ports)

                        if len(flattened_ports):
                            new_challenge.ports = flattened_ports
                        else:
                            new_challenge.ports = '****no exposed ports****'

                    except Exception as e:
                        #raise Exception('Error parsing uploaded Dockerfile: ', e)
                        print('Error parsing uploaded Dockerfile: ', e)
                        new_challenge.ports = '****error parsing ports****'

            #set var for pathPrefix and tag
            #path_tag = str(new_challenge.id) + '_' + re.sub('[^A-Za-z0-9]+', '', new_challenge.category.name.lower()) + str(new_challenge.points)
            path_tag = 'chall_' + str(new_challenge.id)
            new_challenge.pathPrefix = path_tag

            if new_challenge.upload:
                if new_challenge.hosted:

                    image_name = path_tag + ':latest'
                    new_challenge.imageName = image_name

                    #build image
                    build = d.buildImage(
                        fileobj=form.cleaned_data['upload'].file, tag=path_tag)

                    #if build fails set vars as such
                    if not build:
                        error_msg = "****build image failed****"
                        new_challenge.pathPrefix = error_msg
                        new_challenge.imageName = error_msg

                    new_challenge.upload.save(form.cleaned_data['upload'].name,
                                              new_challenge.upload)
                    rethink_data = {
                        'sid': new_challenge.id,
                        'category': new_challenge.category.id,
                        'title': new_challenge.title,
                        'points': new_challenge.points,
                        'description': new_challenge.description,
                        'hosted': new_challenge.hosted,
                        'fileUpload': new_challenge.fileUpload,
                        'imageName': new_challenge.imageName,
                        'ports': new_challenge.ports,
                        'pathPrefix': new_challenge.pathPrefix,
                        'created': format(new_challenge.created, 'U')
                    }

                elif new_challenge.fileUpload:
                    print('fileUpload')
                    new_challenge.upload.save(form.cleaned_data['upload'].name,
                                              new_challenge.upload)
                    rethink_data = {
                        'sid': new_challenge.id,
                        'category': new_challenge.category.id,
                        'title': new_challenge.title,
                        'points': new_challenge.points,
                        'description': new_challenge.description,
                        'hosted': new_challenge.hosted,
                        'fileUpload': new_challenge.fileUpload,
                        'pathPrefix': new_challenge.pathPrefix,
                        'downloadPath': new_challenge.upload.url,
                        'created': format(new_challenge.created, 'U')
                    }
            else:
                #doesn't have a file uploaded
                rethink_data = {
                    'sid': new_challenge.id,
                    'category': new_challenge.category.id,
                    'title': new_challenge.title,
                    'points': new_challenge.points,
                    'description': new_challenge.description,
                    'hosted': new_challenge.hosted,
                    'fileUpload': new_challenge.fileUpload,
                    'imageName': new_challenge.imageName,
                    'ports': new_challenge.ports,
                    'pathPrefix': new_challenge.pathPrefix,
                    'created': format(new_challenge.created, 'U')
                }

            new_challenge.save()

            # Push the realtime data to rethinkdb
            connection = r.connect(host=RDB_HOST, port=RDB_PORT)
            try:
                r.db(CTF_DB).table('challenges').insert(rethink_data).run(
                    connection)
            except RqlRuntimeError as e:
                #raise Exception('Error adding challenge to realtime database: %s' % (e))
                print('Error adding challenge to realtime database: %s' % (e))
            finally:
                connection.close()

            return redirect('challenge_detail', pk=new_challenge.pk)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = ChallengeForm()

    return render(request, 'adminpanel/challenges/challenge_edit.html',
                  {'form': form})
Exemplo n.º 47
0
 def test_microsecond(self):
     # Regression test for #18951
     dt = datetime(2009, 5, 16, microsecond=123)
     self.assertEqual(dateformat.format(dt, 'u'), '000123')
Exemplo n.º 48
0
    def test_date_formats(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)
        timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)

        self.assertEqual(dateformat.format(my_birthday, 'A'), 'PM')
        self.assertEqual(dateformat.format(timestamp, 'c'),
                         '2008-05-19T11:45:23.123456')
        self.assertEqual(dateformat.format(my_birthday, 'd'), '08')
        self.assertEqual(dateformat.format(my_birthday, 'j'), '8')
        self.assertEqual(dateformat.format(my_birthday, 'l'), 'Sunday')
        self.assertEqual(dateformat.format(my_birthday, 'L'), 'False')
        self.assertEqual(dateformat.format(my_birthday, 'm'), '07')
        self.assertEqual(dateformat.format(my_birthday, 'M'), 'Jul')
        self.assertEqual(dateformat.format(my_birthday, 'b'), 'jul')
        self.assertEqual(dateformat.format(my_birthday, 'n'), '7')
        self.assertEqual(dateformat.format(my_birthday, 'N'), 'July')
Exemplo n.º 49
0
 def test_datetime_with_local_tzinfo(self):
     ltz = get_default_timezone()
     dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz)
     self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
     self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))),
                      dt.replace(tzinfo=None))
Exemplo n.º 50
0
 def test_epoch(self):
     udt = datetime(1970, 1, 1, tzinfo=utc)
     self.assertEqual(format(udt, 'U'), '0')
Exemplo n.º 51
0
 def test_date(self):
     d = date(2009, 5, 16)
     self.assertEqual(date.fromtimestamp(int(format(d, 'U'))), d)
Exemplo n.º 52
0
 def test_naive_datetime(self):
     dt = datetime(2009, 5, 16, 5, 30, 30)
     self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt)
Exemplo n.º 53
0
def getCurrentTimeStamp():
	return dateformat.format(timezone.now(), 'U')
Exemplo n.º 54
0
    def test_timezones(self):
        my_birthday = datetime(1979, 7, 8, 22, 00)
        summertime = datetime(2005, 10, 30, 1, 00)
        wintertime = datetime(2005, 10, 30, 4, 00)
        timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)

        # 3h30m to the west of UTC
        tz = get_fixed_timezone(-210)
        aware_dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)

        if TZ_SUPPORT:
            self.assertEqual(dateformat.format(my_birthday, 'O'), '+0100')
            self.assertEqual(dateformat.format(my_birthday, 'r'),
                             'Sun, 8 Jul 1979 22:00:00 +0100')
            self.assertEqual(dateformat.format(my_birthday, 'T'), 'CET')
            self.assertEqual(dateformat.format(my_birthday, 'e'), '')
            self.assertEqual(dateformat.format(aware_dt, 'e'), '-0330')
            self.assertEqual(dateformat.format(my_birthday, 'U'), '300315600')
            self.assertEqual(dateformat.format(timestamp, 'u'), '123456')
            self.assertEqual(dateformat.format(my_birthday, 'Z'), '3600')
            self.assertEqual(dateformat.format(summertime, 'I'), '1')
            self.assertEqual(dateformat.format(summertime, 'O'), '+0200')
            self.assertEqual(dateformat.format(wintertime, 'I'), '0')
            self.assertEqual(dateformat.format(wintertime, 'O'), '+0100')

        # Ticket #16924 -- We don't need timezone support to test this
        self.assertEqual(dateformat.format(aware_dt, 'O'), '-0330')
Exemplo n.º 55
0
def export_as_xls3(
        queryset,
        fields=None,
        header=None,  # noqa
        filename=None,
        options=None,
        out=None):  # pragma: no cover
    # sheet_name=None,  header_alt=None,
    # formatting=None, out=None):
    """
    Exports a queryset as xls from a queryset with the given fields.

    :param queryset: queryset to export (can also be list of namedtuples)
    :param fields: list of fields names to export. None for all fields
    :param header: if True, the exported file will have the first row as column names
    :param out: object that implements File protocol.
    :param header_alt: if is not None, and header is True, the first row will be as header_alt (same nr columns)
    :param formatting: if is None will use formatting_default
    :return: HttpResponse instance if out not supplied, otherwise out
    """
    import xlsxwriter

    def _get_qs_formats(queryset):
        formats = {'_general_': book.add_format()}
        if hasattr(queryset, 'model'):
            for i, fieldname in enumerate(fields):
                try:
                    f, __, __, __, = queryset.model._meta.get_field_by_name(
                        fieldname)
                    pattern = xlsxwriter_options.get(
                        f.name,
                        xlsxwriter_options.get(f.__class__.__name__,
                                               'general'))
                    fmt = book.add_format({'num_format': pattern})
                    formats[fieldname] = fmt
                except FieldDoesNotExist:
                    pass
                    # styles[i] = xlwt.easyxf(num_format_str=xls_options_default.get(col_class, 'general'))
                    # styles[i] = xls_options_default.get(col_class, 'general')

        return formats

    http_response = out is None
    if out is None:
        # if filename is None:
        # filename = filename or "%s.xls" % queryset.model._meta.verbose_name_plural.lower().replace(" ", "_")
        # response = HttpResponse(content_type='application/vnd.ms-excel')
        # response['Content-Disposition'] = 'attachment;filename="%s"' % filename.encode('us-ascii', 'replace')
        # out = io.BytesIO()

        if six.PY2:
            out = six.StringIO()
        elif six.PY3:
            out = six.StringIO()
            # out = io.BytesIO()
        else:
            raise EnvironmentError('Python version not supported')

    config = xlsxwriter_options.copy()
    if options:
        config.update(options)

    if fields is None:
        fields = [
            f.name for f in queryset.model._meta.fields +
            queryset.model._meta.many_to_many
        ]

    book = xlsxwriter.Workbook(out, {'in_memory': True})
    sheet_name = config.pop('sheet_name')
    use_display = config.get('use_display', False)
    sheet = book.add_worksheet(sheet_name)
    book.close()
    formats = _get_qs_formats(queryset)

    row = 0
    sheet.write(row, 0, force_text('#'), formats['_general_'])
    if header:
        if not isinstance(header, (list, tuple)):
            header = [
                force_text(f.verbose_name)
                for f in queryset.model._meta.fields +
                queryset.model._meta.many_to_many if f.name in fields
            ]

        for col, fieldname in enumerate(header, start=1):
            sheet.write(row, col, force_text(fieldname), formats['_general_'])

    settingstime_zone = get_default_timezone()

    for rownum, row in enumerate(queryset):
        sheet.write(rownum + 1, 0, rownum + 1)
        for idx, fieldname in enumerate(fields):
            fmt = formats.get(fieldname, formats['_general_'])
            try:
                value = get_field_value(row,
                                        fieldname,
                                        usedisplay=use_display,
                                        raw_callable=False)
                if callable(fmt):
                    value = fmt(value)
                if isinstance(value, (list, tuple)):
                    value = smart_text(u"".join(value))

                if isinstance(value, datetime.datetime):
                    try:
                        value = dateformat.format(
                            value.astimezone(settingstime_zone),
                            config['datetime_format'])
                    except ValueError:
                        value = dateformat.format(value,
                                                  config['datetime_format'])

                if isinstance(value, six.binary_type):
                    value = smart_text(value)

                    sheet.write(rownum + 1, idx + 1, smart_text(value), fmt)
            except Exception as e:
                raise
                sheet.write(rownum + 1, idx + 1, smart_text(e), fmt)

    book.close()
    out.seek(0)
    if http_response:
        if filename is None:
            filename = filename or "%s.xls" % queryset.model._meta.verbose_name_plural.lower(
            ).replace(" ", "_")
        response = HttpResponse(
            out.read(),
            content_type=
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        # content_type='application/vnd.ms-excel')
        # response['Content-Disposition'] = six.b('attachment;filename="%s"') % six.b(filename.encode('us-ascii', 'replace'))
        response['Content-Disposition'] = six.b('attachment;filename="%s"' %
                                                filename)
        return response
    return out
Exemplo n.º 56
0
def getTimeStamp(dateTimeObject):
	return dateformat.format(dateTimeObject, 'U')
Exemplo n.º 57
0
 def __unicode__(self):
     return ', '.join(
         (dateformat.format(self.date,
                            'd E Y'), self.product.name, self.address))
Exemplo n.º 58
0
def rule_to_text(rule, short=False):
    """
    Render the given `Rule` as natural text.

    :Parameters:
        `short` : bool
            Use abbreviated labels, i.e. 'Fri' instead of 'Friday'.
    """
    frequencies = (
        _('annually'),
        _('monthly'),
        _('weekly'),
        _('daily'),
        _('hourly'),
        _('minutely'),
        _('secondly'),
    )
    timeintervals = (
        _('years'),
        _('months'),
        _('weeks'),
        _('days'),
        _('hours'),
        _('minutes'),
        _('seconds'),
    )

    if short:
        positional_display = {
            1: _('1st %(weekday)s'),
            2: _('2nd %(weekday)s'),
            3: _('3rd %(weekday)s'),
            -1: _('last %(weekday)s'),
            -2: _('2nd last %(weekday)s'),
            -3: _('3rd last %(weekday)s'),
        }
        weekdays_display = (
            _('Mon'),
            _('Tue'),
            _('Wed'),
            _('Thu'),
            _('Fri'),
            _('Sat'),
            _('Sun'),
        )
        months_display = (
            _('Jan'),
            _('Feb'),
            _('Mar'),
            _('Apr'),
            _p('month name', 'May'),
            _('Jun'),
            _('Jul'),
            _('Aug'),
            _('Sep'),
            _('Oct'),
            _('Nov'),
            _('Dec'),
        )

    else:
        positional_display = {
            1: _('first %(weekday)s'),
            2: _('second %(weekday)s'),
            3: _('third %(weekday)s'),
            4: _('fourth %(weekday)s'),
            -1: _('last %(weekday)s'),
            -2: _('second last %(weekday)s'),
            -3: _('third last %(weekday)s'),
        }
        weekdays_display = (
            _('Monday'),
            _('Tuesday'),
            _('Wednesday'),
            _('Thursday'),
            _('Friday'),
            _('Saturday'),
            _('Sunday'),
        )
        months_display = (
            _('January'),
            _('February'),
            _('March'),
            _('April'),
            _p('month name', 'May'),
            _('June'),
            _('July'),
            _('August'),
            _('September'),
            _('October'),
            _('November'),
            _('December'),
        )

    def get_positional_weekdays(rule):
        items = []
        if rule.bysetpos and rule.byday:
            for setpos in rule.bysetpos:
                for byday in rule.byday:
                    byday = to_weekday(byday)
                    items.append(
                        positional_display.get(setpos) %
                        {'weekday': weekdays_display[byday.number]})
        elif rule.byday:
            for byday in rule.byday:
                byday = to_weekday(byday)
                items.append(
                    positional_display.get(byday.index, '%(weekday)s') %
                    {'weekday': weekdays_display[byday.number]})
        return _(', ').join(items)

    parts = []

    if rule.interval > 1:
        parts.append(
            _('every %(number)s %(freq)s') % {
                'number': rule.interval,
                'freq': timeintervals[rule.freq]
            })
    else:
        parts.append(frequencies[rule.freq])

    if rule.freq == YEARLY:
        if rule.bymonth:
            # bymonths are 1-indexed (January is 1), months_display
            # are 0-indexed (January is 0).
            items = _(', ').join([
                months_display[month]
                for month in [month_index - 1 for month_index in rule.bymonth]
            ])
            parts.append(_('each %(items)s') % {'items': items})
        if rule.byday or rule.bysetpos:
            parts.append(
                _('on the %(items)s') %
                {'items': get_positional_weekdays(rule)})

    if rule.freq == MONTHLY:
        if rule.bymonthday:
            items = _(', ').join([
                dateformat.format(datetime.datetime(1, 1, day), 'jS')
                for day in rule.bymonthday
            ])
            parts.append(_('on the %(items)s') % {'items': items})
        elif rule.byday:
            if rule.byday or rule.bysetpos:
                parts.append(
                    _('on the %(items)s') %
                    {'items': get_positional_weekdays(rule)})

    if rule.freq == WEEKLY:
        if rule.byday:
            items = _(', ').join([
                weekdays_display[to_weekday(day).number] for day in rule.byday
            ])
            parts.append(_('each %(items)s') % {'items': items})

    # daily freqencies has no additional formatting,
    # hour/minute/second formatting not supported

    if rule.count:
        if rule.count == 1:
            parts.append(_('occuring once'))
        else:
            parts.append(
                _('occuring %(number)s times') % {'number': rule.count})
    elif rule.until:
        parts.append(
            _('until %(date)s') %
            {'date': dateformat.format(rule.until, 'Y-m-d')})

    return _(', ').join(parts)
Exemplo n.º 59
0
def log_to(querydict):
    # 日付ごとのログ抽出時の対象日付
    log_to = querydict.get('log_to')
    if log_to is None or log_to == "/":
        log_to = dateformat.format(datetime.now(), 'Y-m-d')
    return log_to
Exemplo n.º 60
0
 def render_finalized(self, value):
     if value in [None, u'']:
         return u''
     return format_html(u'{0}', format(value, self.final_format))