def process(self, format=None, user=None): if user is None: user = self.context.get('user') qs = self.get_queryset() qs = qs.published(user=user) return date_format(self.get_date(qs), format)
def __str__(self): if self.message: subject = " - '%s'" % self.message.strip().split('\n')[0] else: subject = '' date = date_format(self.created_at, 'DATETIME_FORMAT') return '#%s %s%s' % (self.id, date, subject)
def timestamp_(self, instance): url = reverse('admin:%s_%s_change' % (instance._meta.app_label, instance._meta.module_name), args=(instance.id, )) return format_html( u'<a href="{}">{}</a>', url, date_format(instance.timestamp, settings.DATETIME_FORMAT))
def __unicode__(self): if self.message: subject = " - '%s'" % self.message.strip().split('\n')[0] else: subject = '' date = date_format(self.created_at, 'DATETIME_FORMAT') return '#%s %s%s' % (self.id, date, subject)
def __str__(self): log = '' if self.display: log = '{} {} at {}'.format( self.text, self.display_status, date_format(self.date).capitalize(), ) return log
def json_dict(self, selfurl): ts = dict() ts['timeslot_id'] = self.id ts['room'] = slugify(self.location) ts['roomtype'] = self.type.slug ts["time"] = date_format(self.time, 'Hi') ts["date"] = time_format(self.time, 'Y-m-d') ts["domid"] = self.js_identifier return ts
def frontend_message(self): try: type_object = self.type_object except ValueError: type_object = '' return '{} {} on {}'.format( type_object, self.display_status, date_format(self.date).capitalize(), )
def timestamp_(self, instance): url = reverse( 'admin:%s_%s_change' % ( instance._meta.app_label, instance._meta.module_name ), args=(instance.id,) ) return format_html( u'<a href="{}">{}</a>', url, date_format(instance.timestamp, settings.DATETIME_FORMAT) )
def to_representation(self, instance): ret = super( BankTransactionDetailSerializer, self).to_representation(instance) ret['date_view'] = date_format(instance.date, 'SHORT_DATE_FORMAT') ret['amount_localized'] = localize_signed_amount(instance.amount) ret['amount_currency'] = localize_signed_amount_currency( instance.amount, instance.currency) ret['payment_method_display'] = instance.get_payment_method_display() ret['status_display'] = instance.get_status_display() return ret
def json_dict(self, selfurl): ss = dict() ss['assignment_id'] = self.id #ss['href'] = self.url(sitefqdn) ss['empty'] = self.empty_str ss['timeslot_id'] = self.timeslot.id if self.session: ss['session_id'] = self.session.id ss['room'] = slugify(self.timeslot.location) ss['roomtype'] = self.timeslot.type.slug ss["time"] = date_format(self.timeslot.time, 'Hi') ss["date"] = time_format(self.timeslot.time, 'Y-m-d') ss["domid"] = self.timeslot.js_identifier return ss
def json_dict(self, selfurl): ss = dict() ss['scheduledsession_id'] = self.id #ss['href'] = self.url(sitefqdn) ss['empty'] = self.empty_str ss['timeslot_id'] = self.timeslot.id if self.session: ss['session_id'] = self.session.id ss['room'] = slugify(self.timeslot.location) ss['roomtype'] = self.timeslot.type.slug ss["time"] = date_format(self.timeslot.time, 'Hi') ss["date"] = time_format(self.timeslot.time, 'Y-m-d') ss["domid"] = self.timeslot.js_identifier return ss
def json_dict(self, host_scheme): ts = dict() ts['timeslot_id'] = self.id ts['href'] = urljoin(host_scheme, self.json_url()) ts['room'] = self.get_location() ts['roomtype'] = self.type.slug if self.location is not None: ts['capacity'] = self.location.capacity ts["time"] = date_format(self.time, 'Hi') ts["date"] = fmt_date(self.time) ts["domid"] = self.js_identifier following = self.slot_to_the_right if following is not None: ts["following_timeslot_id"] = following.id return ts
def get_comment_action_text(comment): user_frag = '<a href="{url}">{user}</a>' date_frag = '<span title="{title}">{date}</span>' text_frag = ACTIONS.get(comment.action, "{user} unknown action {time_ago}") if comment.is_removed: text_frag = _("{user}'s comment was removed {time_ago}") return format_html( text_frag, user=format_html( user_frag, url=comment.user.st.get_absolute_url(), user=comment.user.st.nickname), time_ago=format_html( date_frag, title=date_format(comment.date, "DATETIME_FORMAT"), date=humanize.naturaltime(comment.date)))
def user_log_export(request): lists = get_user_log_lists(request) lists = lists[:1000] lists2 = [[ _(u'序号'), _(u'时间'), _(u'用户名'), _(u'真实姓名'), _(u'邮箱'), _(u'手机号'), _(u'微信昵称'), _(u'头像'), _(u'操作类型'), _(u'模块动作'), _(u'结果'), _(u'详情'), _(u'客户端IP'), ]] current_row = 1 for d in lists: name, realname, mailbox, tel_mobile, nickname, img = "", "", "", "", "", "" # d,mailbox 可能为None m = d.mailbox if hasattr(d, "mailbox") else None if m: name, mailbox = m.name, m.username u = m.user if u: realname, tel_mobile = u.realname, u.tel_mobile w = d.wxuser if w: nickname, img = w.nickname, w.img lists2.append([ current_row, date_format(d.datetime, 'Y-m-d H:i'), name, realname, mailbox, tel_mobile, nickname, img, d.get_classify_display(), d.action, d.get_result_display(), d.description, d.clientip ]) current_row += 1 return ExcelResponse(lists2, "user_log", encoding='gbk')
def log(request, template_name=TEMPLATE_NAME, template_name_ajax=TEMPLATE_NAME_AJAX): """Get log entries. Serves both non-AJAX and AJAX driven requests. Since we have a breakdown of entries per day per entry and we have an AJAX driven infinite scroll and we want to avoid having duplicated date headers, we always pass a variable named "last_date" when making another request to our main AJAX-driven view. So... this is our case scenario: Initial timeline rendered as a normal HTML (non AJAX request) (from a list of log entries). We send date of last element as "last_date" to the context too, which will be used an an initial value for a global JavaScript variable. Later on that date will be used to send it to the AJAX driven view and used in rendering ("render_to_string" method). After we have rendered the HTML to send back, we get the last date of the last element and send it along with the HTML rendered to our view in JSON response. When receiving the JSON response, we update the above mentioned global JavaScript variable with the value given. :param request: django.http.HttpRequest :param template_name: str :param template_name_ajax: str :return: django.http.HttpResponse This view accepts the following POST variables (all optional). :param page: int - Page number to get. :param user_id: int - If set, used to filter the user by. :param last_date: str - Example value "2012-05-24". :param start_date: str - If set, used as a start date to filter the actions with. Example value "2012-05-24". :param end_date: str - If set, used as an end date to filter the actions with. Example value "2012-05-24". NOTE: If it gets too complicatd with filtering, we need to have forms to validate and process the POST data. """ def _get_date_from_string(val): """Get date from a string given. :param str val: - date in string format :return: datetime.datetime """ try: return datetime.date(*map(lambda x: int(x), val.split("-"))) except Exception as err: return "" try: page = int(request.POST.get('page', 1)) if page < 1: page = 1 except Exception as err: page = 1 users = [] content_types = [] filter_form = None if 'POST' == request.method: post = dict(request.POST) if 'users[]' in post: post['users'] = post.pop('users[]') elif 'users' in post: post['users'] = post.pop('users') if SIMPLE_FILTER_FORM: if 'users' in post and post['users']: post['users'] = post['users'][0] if 'content_types[]' in post: post['content_types'] = post.pop('content_types[]') elif 'content_types' in post: post['content_types'] = post.pop('content_types') if SIMPLE_FILTER_FORM: if 'content_types' in post and post['content_types']: post['content_types'] = post['content_types'][0] filter_form = FilterForm(post) if filter_form.is_valid(): users = filter_form.cleaned_data['users'] content_types = filter_form.cleaned_data['content_types'] if SIMPLE_FILTER_FORM: if users: users = [ int(_u.strip()) for _u in users.split(',') if _u.strip() ] else: users = [] if content_types: content_types = [ int(_c.strip()) for _c in content_types.split(',') if _c.strip() ] else: content_types = [] else: pass # Anything to do here? else: filter_form = FilterForm() # Some kind of a pagination start = (page - 1) * NUMBER_OF_ENTRIES_PER_PAGE end = page * NUMBER_OF_ENTRIES_PER_PAGE # Getting admin log entries taking page number into consideration. log_entries = LogEntry.objects.all().select_related('content_type', 'user') start_date = _get_date_from_string(request.POST.get('start_date')) end_date = _get_date_from_string(request.POST.get('end_date')) if start_date: log_entries = log_entries.filter(action_time__gte=start_date) # TODO if end_date: log_entries = log_entries.filter(action_time__lte=end_date) # TODO # If users given, filtering by users if users: log_entries = log_entries.filter(user__id__in=users) # If content types given, filtering by content types if content_types: log_entries = log_entries.filter(content_type__id__in=content_types) # Applying limits / freezing the queryset log_entries = log_entries[start:end] if log_entries: last_date = date_format(log_entries[len(log_entries) - 1].action_time, "Y-m-d") else: last_date = request.POST.get('last_date', None) # Using different template for AJAX driven requests if request.is_ajax(): # Context to render the AJAX driven HTML with context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': request.POST.get('last_date', None), 'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT, 'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT } # Rendering HTML for an AJAX driven request if versions.DJANGO_GTE_1_10: html = render_to_string(template_name_ajax, context, request=request) else: html = render_to_string(template_name_ajax, context, context_instance=RequestContext(request)) # Context to send back to user in a JSON response context = { 'html': html, 'last_date': last_date, 'success': 1 if len(log_entries) else 0 } return HttpResponse(json.dumps(context)) # Context for a non-AJAX request context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': last_date, 'start_date': date_format(start_date, "Y-m-d") if start_date else "", 'end_date': date_format(end_date, "Y-m-d") if end_date else "", 'users': [int(u) for u in users], 'content_types': [int(ct) for ct in content_types], 'filter_form': filter_form, 'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT, 'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT, 'title': _("Timeline") # For template breadcrumbs, etc. } if versions.DJANGO_GTE_1_10: return render(request, template_name, context) else: return render_to_response(template_name, context, context_instance=RequestContext(request))
if end_date: log_entries = log_entries.filter(action_time__lte=end_date) # TODO # If users given, filtering by users if users: log_entries = log_entries.filter(user__id__in=users) # If content types given, filtering by content types if content_types: log_entries = log_entries.filter(content_type__id__in=content_types) # Applying limits / freezing the queryset log_entries = log_entries[start:end] if log_entries: last_date = date_format(log_entries[len(log_entries) - 1].action_time, "Y-m-d") else: last_date = request.POST.get('last_date', None) # Using different template for AJAX driven requests if request.is_ajax(): # Context to render the AJAX driven HTML with context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': request.POST.get('last_date', None), 'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT, 'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT }
def get_history_data(queryset): resources = {} needs_aggregation = False for rdata in queryset: resource = rdata.resource try: (options, aggregation) = resources[resource] except KeyError: aggregation = resource.aggregation_instance options = { 'aggregation': str(aggregation.verbose_name), 'aggregated_history': aggregation.aggregated_history, 'content_type': rdata.content_type.model, 'content_object': rdata.content_object_repr, 'unit': resource.unit, 'scale': resource.get_scale(), 'verbose_name': str(resource.verbose_name), 'dates': set() if aggregation.aggregated_history else None, 'objects': [], } resources[resource] = (options, aggregation) if aggregation.aggregated_history: needs_aggregation = True monitors = [] scale = options['scale'] all_dates = options['dates'] for monitor_name, dataset in rdata.get_monitor_datasets(): datasets = {} for content_object, datas in aggregation.aggregate_history( dataset): if aggregation.aggregated_history: serie = {} for data in datas: value = round(float(data.value) / scale, 3) if data.value is not None else None all_dates.add(data.date) serie[data.date] = value else: serie = [] for data in datas: date = data.created_at.timestamp() date = int(str(date).split('.')[0] + '000') value = round(float(data.value) / scale, 3) if data.value is not None else None serie.append((date, value)) datasets[content_object] = serie monitors.append({ 'name': monitor_name, 'datasets': datasets, }) options['objects'].append({ 'object_name': rdata.content_object_repr, 'current': round(float(rdata.used or 0), 3), 'allocated': float(rdata.allocated) if rdata.allocated is not None else None, 'updated_at': rdata.updated_at.isoformat() if rdata.updated_at else None, 'monitors': monitors, }) if needs_aggregation: result = [] for options, aggregation in resources.values(): if aggregation.aggregated_history: all_dates = sorted(options['dates']) options['dates'] = [date_format(date) for date in all_dates] for obj in options['objects']: for monitor in obj['monitors']: series = [] for content_object, dataset in monitor[ 'datasets'].items(): data = [] for date in all_dates: data.append(dataset.get(date, 0.0)) series.append({ 'name': content_object, 'data': data, }) monitor['datasets'] = series result.append(options) else: result = [resource[0] for resource in resources.values()] return result
def log(request, template_name=TEMPLATE_NAME, \ template_name_ajax=TEMPLATE_NAME_AJAX): """ Get number of log entires. Serves both non-AJAX and AJAX driven requests. Since we have a breakdown of entries per day per entry and we have an AJAX driven infinite scroll and we want to avoid having duplicated date headers, we always pass a variable named "last_date" when making another request to our main AJAX-driven view. So... this is our case scenario: Initial timeline rendered as a normal HTML (non AJAX request) (from a list of log entries). We send date of last element as "last_date" to the context too, which will be used an an initial value for a global JavaScript variable. Later on that date will be used to send it to the AJAX driven view and used in rendering ("render_to_string" method). After we have rendered the HTML to send back, we get the last date of the last element and send it along with the HTML rendered to our view in JSON response. When receiving the JSON response, we update the above mentioned global JavaScript variable with the value given. :param request: django.http.HttpRequest :param template_name: str :param template_name_ajax: str :return: django.http.HttpResponse This view accepts the following POST variables (all optional). :param page: int - Page number to get. :param user_id: int - If set, used to filter the user by. :param last_date: str - Example value "2012-05-24". :param start_date: str - If set, used as a start date to filter the actions with. Example value "2012-05-24". :param end_date: str - If set, used as an end date to filter the actions with. Example value "2012-05-24". NOTE: If it gets too complicatd with filtering, we need to have forms to validate and process the POST data. """ def _get_date_from_string(s): """ Gets date from a string given. :param s: str - date in string format :return: datetime.datetime """ try: return datetime.date(*map(lambda x: int(x), s.split("-"))) except Exception as e: return "" try: page = int(request.POST.get('page', 1)) if page < 1: page = 1 except Exception as e: page = 1 users = [] content_types = [] filter_form = None if 'POST' == request.method: post = dict(request.POST) if 'users[]' in post: post['users'] = post.pop('users[]') if 'content_types[]' in post: post['content_types'] = post.pop('content_types[]') filter_form = FilterForm(post) if filter_form.is_valid(): users = filter_form.cleaned_data['users'] content_types = filter_form.cleaned_data['content_types'] else: pass # Anything to do here? else: filter_form = FilterForm() # Some kind of a pagination start = (page - 1) * NUMBER_OF_ENTRIES_PER_PAGE end = page * NUMBER_OF_ENTRIES_PER_PAGE # Getting admin log entires taking page number into consideration. log_entries = LogEntry.objects.all().select_related('content_type', 'user') start_date = _get_date_from_string(request.POST.get('start_date')) end_date = _get_date_from_string(request.POST.get('end_date')) if start_date: log_entries = log_entries.filter(action_time__gte=start_date) # TODO if end_date: log_entries = log_entries.filter(action_time__lte=end_date) # TODO # If users given, filtering by users if users: log_entries = log_entries.filter(user__id__in=users) # If content types given, filtering by content types if content_types: log_entries = log_entries.filter(content_type__id__in=content_types) # Applying limits / freezing the queryset log_entries = log_entries[start:end] if log_entries: last_date = date_format( log_entries[len(log_entries) - 1].action_time, "Y-m-d" ) else: last_date = request.POST.get('last_date', None) # Using different template for AJAX driven requests if request.is_ajax(): # Context to render the AJAX driven HTML with context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': request.POST.get('last_date', None), 'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT, 'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \ LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT } # Rendering HTML for an AJAX driven request html = render_to_string( template_name_ajax, context, context_instance=RequestContext(request) ) # Context to send back to user in a JSON response context = { 'html': html, 'last_date': last_date, 'success': 1 if len(log_entries) else 0 } return HttpResponse(json.dumps(context)) # Context for a non-AJAX request context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': last_date, 'start_date': date_format(start_date, "Y-m-d") if start_date else "", 'end_date': date_format(end_date, "Y-m-d") if end_date else "", 'users': [int(u) for u in users], 'content_types': [int(ct) for ct in content_types], 'filter_form': filter_form, 'SINGLE_LOG_ENTRY_DATE_FORMAT': SINGLE_LOG_ENTRY_DATE_FORMAT, 'LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT': \ LOG_ENTRIES_DAY_HEADINGS_DATE_FORMAT, 'title': _("Timeline") # For template breadcrumbs, etc. } return render_to_response( template_name, context, context_instance=RequestContext(request) )
def __unicode__(self): return u'%s: %s (%s)' % (self.category.name, self.score, date_format(self.edition.date, 'N d, Y'))
def date_range(start_date, end_date): if start_date.precision != end_date.precision: return "%s - %s" % (start_date.explicit_format(), end_date.explicit_format()) elif start_date.precision == 'y': if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format(start_date.date, arg="Y"), date_format(end_date.date, arg="Y")) else: return date_format(start_date.date, arg="Y") elif start_date.precision == 'm': if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format(start_date.date, arg="F Y"), date_format(end_date.date, arg="F Y")) elif start_date.date.month != end_date.date.month: return "%s - %s" % (date_format(start_date.date, arg="F"), date_format(end_date.date, arg="F Y")) else: return date_format(start_date.date, arg="F Y") else: if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format(start_date.date, arg="jS F Y"), date_format(end_date.date, arg="jS F Y")) elif start_date.date.month != end_date.date.month: return "%s - %s" % (date_format(start_date.date, arg="jS F"), date_format(end_date.date, arg="jS F Y")) elif start_date.date.day != end_date.date.day: return "%s - %s" % (date_format(start_date.date, arg="jS"), date_format(end_date.date, arg="jS F Y")) else: return date_format(start_date.date, arg="jS F Y")
def date_range(start_date, end_date): if start_date.precision != end_date.precision: return "%s - %s" % (start_date.explicit_format(), end_date.explicit_format()) elif start_date.precision == 'y': if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format( start_date.date, arg="Y"), date_format(end_date.date, arg="Y")) else: return date_format(start_date.date, arg="Y") elif start_date.precision == 'm': if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format(start_date.date, arg="F Y"), date_format(end_date.date, arg="F Y")) elif start_date.date.month != end_date.date.month: return "%s - %s" % (date_format(start_date.date, arg="F"), date_format(end_date.date, arg="F Y")) else: return date_format(start_date.date, arg="F Y") else: if start_date.date.year != end_date.date.year: return "%s - %s" % (date_format(start_date.date, arg="jS F Y"), date_format(end_date.date, arg="jS F Y")) elif start_date.date.month != end_date.date.month: return "%s - %s" % (date_format(start_date.date, arg="jS F"), date_format(end_date.date, arg="jS F Y")) elif start_date.date.day != end_date.date.day: return "%s - %s" % (date_format(start_date.date, arg="jS"), date_format(end_date.date, arg="jS F Y")) else: return date_format(start_date.date, arg="jS F Y")
def get_week_day(self, sale): if not sale.purchase_date: return "-" return date_format(sale.purchase_date, "l")
def get_history_data(queryset): resources = {} needs_aggregation = False for rdata in queryset: resource = rdata.resource try: (options, aggregation) = resources[resource] except KeyError: aggregation = resource.aggregation_instance options = { 'aggregation': str(aggregation.verbose_name), 'aggregated_history': aggregation.aggregated_history, 'content_type': rdata.content_type.model, 'content_object': rdata.content_object_repr, 'unit': resource.unit, 'scale': resource.get_scale(), 'verbose_name': str(resource.verbose_name), 'dates': set() if aggregation.aggregated_history else None, 'objects': [], } resources[resource] = (options, aggregation) monitors = [] scale = options['scale'] all_dates = options['dates'] for monitor_name, dataset in rdata.get_monitor_datasets(): datasets = {} for content_object, datas in aggregation.aggregate_history(dataset): if aggregation.aggregated_history: needs_aggregation = True serie = {} for data in datas: value = round(float(data.value)/scale, 3) if data.value is not None else None all_dates.add(data.date) serie[data.date] = value else: serie = [] for data in datas: date = data.created_at.timestamp() date = int(str(date).split('.')[0] + '000') value = round(float(data.value)/scale, 3) if data.value is not None else None serie.append( (date, value) ) datasets[content_object] = serie monitors.append({ 'name': monitor_name, 'datasets': datasets, }) options['objects'].append({ 'object_name': rdata.content_object_repr, 'current': round(float(rdata.used), 3), 'allocated': float(rdata.allocated) if rdata.allocated is not None else None, 'updated_at': rdata.updated_at.isoformat(), 'monitors': monitors, }) if needs_aggregation: result = [] for options, aggregation in resources.values(): if aggregation.aggregated_history: all_dates = sorted(options['dates']) options['dates'] = [date_format(date) for date in all_dates] for obj in options['objects']: for monitor in obj['monitors']: series = [] for content_object, dataset in monitor['datasets'].items(): data = [] for date in all_dates: data.append(dataset.get(date, 0.0)) series.append({ 'name': content_object, 'data': data, }) monitor['datasets'] = series result.append(options) else: result = [resource[0] for resource in resources.values()] return result
if end_date: log_entries = log_entries.filter(action_time__lte=end_date) # TODO # If users given, filtering by users if users: log_entries = log_entries.filter(user__id__in=users) # If content types given, filtering by content types if content_types: log_entries = log_entries.filter(content_type__id__in=content_types) # Applying limits / freezing the queryset log_entries = log_entries[start:end] if log_entries: last_date = date_format(log_entries[len(log_entries) - 1].action_time, "Y-m-d") else: last_date = request.POST.get('last_date', None) # Using different template for AJAX driven requests if request.is_ajax(): # Context to render the AJAX driven HTML with context = { 'admin_log': log_entries, 'number_of_entries_per_page': NUMBER_OF_ENTRIES_PER_PAGE, 'page': page, 'last_date': request.POST.get('last_date', None),