def get_context_data(self,**kwargs):
instructor = self.object
context = {}
context.update({
'instructor': instructor,
'prior_series': Event.objects.filter(startTime__lte=timezone.now(),eventstaffmember__staffMember=instructor).order_by('-startTime'),
'upcoming_series': Event.objects.filter(startTime__gt=timezone.now(),eventstaffmember__staffMember=instructor).order_by('-startTime'),
})
if context['prior_series']:
context.update({'first_series': context['prior_series'].last(),})
context.update({
'teaching_since': month_name[context['first_series'].month] + ' ' + str(context['first_series'].year),
'student_count': sum([x.numRegistered for x in context['prior_series']]),
})
context.update({'series_count': len(context['prior_series']) + len(context['upcoming_series'])})
# Note: This get the detailview's context, not all the mixins. Supering itself led to an infinite loop.
return super(DetailView, self).get_context_data(**context)
python类month_name()的实例源码
def get(self,request,*args,**kwargs):
# These are passed via the URL
year = self.kwargs.get('year')
month = self.kwargs.get('month')
slug = self.kwargs.get('slug','')
try:
month_number = list(month_name).index(month or 0)
except ValueError:
raise Http404(_('Invalid month.'))
seriesset = get_list_or_404(Series,~Q(status=Event.RegStatus.hidden),~Q(status=Event.RegStatus.linkOnly),year=year or None,month=month_number or None,classDescription__slug=slug)
# This will pass through to the context data by default
kwargs.update({'seriesset': seriesset})
# For each Series in the set, add a button to the toolbar to edit the Series details
if hasattr(request,'user') and request.user.has_perm('core.change_series'):
for this_series in seriesset:
this_title = _('Edit Class Details')
if len(seriesset) > 1:
this_title += ' (#%s)' % this_series.id
request.toolbar.add_button(this_title, reverse('admin:core_series_change', args=([this_series.id,])), side=RIGHT)
return super(IndividualClassView,self).get(request,*args,**kwargs)
def eventregistration_list(self,obj):
eregs = obj.eventregistration_set.all()
if not eregs:
return ''
return_string = '<ul>'
for ereg in eregs:
this_string = '<li>'
if ereg.cancelled:
this_string += '<em>%s</em> ' % _('CANCELLED:')
if ereg.dropIn:
this_string += '<em>%s</em> ' % _('DROP-IN:')
if ereg.event.month:
this_string += '%s %s, %s</li>' % (month_name[ereg.event.month], ereg.event.year, ereg.event.name)
else:
this_string += '%s</li>' % ereg.event.name
return_string += this_string
return return_string
def bdays_month(month):
if month not in range(1, 13):
abort(400, 'Not a valid month')
# SO questions/36155332
_, num_days = calendar.monthrange(THIS_YEAR, month)
start = date(THIS_YEAR, month, 1)
end = date(THIS_YEAR, month, num_days)
now = _get_current_date()
# TODO: some duplication here with index()
bdays = (Birthday.query.filter(Birthday.bday <= end)
.filter(Birthday.bday >= start))
month_name = calendar.month_name[month][:3]
return render_template("index.html",
data=bdays,
now=now,
active_tab=month_name,
tabs=TABS)
def _set_league_sport_map(league, sport, start_month=None, end_month=None):
'''Set league to sport mapping only if current date within range'''
if not start_month or not end_month:
# year-round league
LEAGUE_SPORT_MAP[league] = sport
return
month_to_num = dict((v,k) for k,v in enumerate(calendar.month_name))
start_month_num = month_to_num[start_month]
end_month_num = month_to_num[end_month]
current_month_num = datetime.datetime.utcnow().month
if start_month_num <= current_month_num <= end_month_num:
LEAGUE_SPORT_MAP[league] = sport
return
if end_month_num < start_month_num:
# range wraps around year
if start_month_num <= current_month_num or current_month_num <= end_month_num:
LEAGUE_SPORT_MAP[league] = sport
return
def test_using_filters(self):
now = datetime.now()
client = self.get_ussd_client()
# dial in
response = client.send('1')
self.assertEqual(
"The date today is {now}. We are on the {now_month} th month "
"and we are on year {now_year}. Month in words is "
"{now_month_name}. And day in words "
"{now_day_name}. And next month {three_months}\n"
"Testing striping date. After striping this "
"date 2017-01-20 we should get the year, month and day. "
"The day is {strip_day_name}\n".format(
now=now,
now_month=now.month,
now_year=now.year,
now_month_name=calendar.month_name[now.month],
now_day_name=now.strftime("%A"),
three_months=calendar.month_name[now.month + 3],
strip_day_name=20
),
response
)
def calendar(self):
pid = int(self.p['pid']) if 'pid' in self.p else -1
now = datetime.datetime.now()
year = int(self.p['year']) if 'year' in self.p else now.year
month = int(self.p['month']) if 'month' in self.p else now.month
show_subtasks = True if 'show' in self.p else False
project_a = projects_sql(self.gid)
if int(pid) > 0:
project = project_name_sql(self.gid, pid)
else:
project = ""
calendar_a = calendar_sql(self.gid, pid, year, month, show_subtasks)
msg_a = msg_sql(self.gid)
return {'user': self.user, 'project_a': project_a, 'pid': pid,
'project': project, 'month_num': month,
'month_name': calendar.month_name[month],
'year': year, 'calendar_a': calendar_a, 'msg_a': msg_a}
def test_month_name(self):
import calendar
m = datetime.now().month
expected = calendar.month_name[m]
result = month_name()
self.assertEqual(expected, result)
def test_last_month_name(self):
import calendar
m = (datetime.now().month - 2) % 12 + 1
expected = calendar.month_name[m]
result = last_month_name()
self.assertEqual(expected, result)
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def get_month_number(self, month):
names = dict((v, k) for k, v in enumerate(calendar.month_name))
abbrs = dict((v, k) for k, v in enumerate(calendar.month_abbr))
month_str = month.title()
try:
return names[month_str]
except KeyError:
try:
return abbrs[month_str]
except KeyError:
return 0
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def dbtc(self):
"""output the calendar of current year in text with month
follow by days on each row"""
current_yr = datetime.date.today().year
global DONE_SYMBOL
DONE_SYMBOL = self.view.settings().get("done_symbol")
init_msg = "** {0} **".format(INITIAL_MESSAGE).center(CALENDAR_WIDTH)
year = "{year}\n".format(year=current_yr).rjust(8, ' ')
txt_builder = []
txt_builder.append(init_msg)
txt_builder.append("\n\n")
txt_builder.append(year)
cal = calendar.Calendar(calendar.MONDAY)
for m, month_name in MONTHS.items():
month = cal.itermonthdays(current_yr, m)
days = "".join(
[get_weekday_format(current_yr, m, day)
for day in month if day != 0]
)
txt_builder.append("{month_name}{days}\n".format(month_name=month_name,
days=days))
return "".join(txt_builder)
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def name(self):
return standardlib_calendar.month_name[self.start.month]
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def test_name(self):
# abbreviations
for i, name in enumerate(calendar.month_abbr[1:]):
self.assertEquals(MonthSetBuilder().build(name), {i + 1})
self.assertEquals(MonthSetBuilder().build(name.lower()), {i + 1})
self.assertEquals(MonthSetBuilder().build(name.upper()), {i + 1})
# full names
for i, name in enumerate(calendar.month_name[1:]):
self.assertEquals(MonthSetBuilder().build(name), {i + 1})
self.assertEquals(MonthSetBuilder().build(name.lower()), {i + 1})
self.assertEquals(MonthSetBuilder().build(name.upper()), {i + 1})
def textDateToInt(txtDate):
for index, item in enumerate(calendar.month_name):
if item[:3] == txtDate:
if len(str(index)) == 1:
return "0" + str(index)
else:
return str(index)
# sort by value of date inside each dict inside parent dict
def textDateToInt(txtDate):
for index, item in enumerate(calendar.month_name):
if item[:3] == txtDate:
if len(str(index)) == 1:
return "0" + str(index)
else:
return str(index)
# sort by value of date inside each dict inside parent dict
def textDateToInt(txtDate):
for index, item in enumerate(calendar.month_name):
if item[:3] == txtDate:
if len(str(index)) == 1:
return "0" + str(index)
else:
return str(index)
# sort by value of date inside each dict inside parent dict
def get_month_number(self, month):
"""Take a string month and return its numberic."""
months = {v: k for k, v in enumerate(calendar.month_name)}
return months[month]
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def MonthlyPerformanceJSON(request):
series = request.GET.get('series')
if series not in ['AvgStudents','Registrations','EventRegistrations','Hours','StudentHours']:
series = 'EventRegistrations'
yearTotals = getMonthlyPerformance()[series]
# Return JSON as lists, not as dictionaries, for c3.js
# yearTotals_list = [dict(v,**{'year':k}) for k, v in yearTotals.items()]
# Now make the lists so that there is one row per month, not one row per year,
# to make things easier for working with c3.js.yearTotals
monthTotals_list = []
years = list(set([k for k,v in yearTotals.items()]))
# Only include calendar months for graphing
for month in range(1,13):
this_month_data = {'month': month, 'month_name': month_name[month]}
for year in years:
this_month_data[year] = yearTotals[year].get(month)
monthTotals_list.append(this_month_data)
monthTotals_list_sorted = sorted(monthTotals_list, key=lambda k: k['month'])
return JsonResponse(monthTotals_list_sorted,safe=False)
def MonthlyPerformanceCSV(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="monthlyPerformance.csv"'
writer = csv.writer(response)
yearTotals = getMonthlyPerformance()
all_years = [k for k in yearTotals['Hours'].keys() if k != 'MonthlyAverage']
all_years.sort()
# Write headers first
headers_list = ['Data Series','Month','All-Time Avg.']
for year in all_years:
headers_list.append(str(year))
writer.writerow(headers_list)
# Note: These are not translated because the chart Javascript looks for these keys
yearTotals_keys = {
'Total Student-Hours': 'StudentHours',
'Avg. Students/Hour': 'AvgStudents',
'Hours of Instruction': 'Hours',
'Unique Registrations': 'Registrations',
'Total Students': 'EventRegistrations',
}
for series,key in yearTotals_keys.items():
for month in range(1,13):
this_row = [
series,
month_name[month],
yearTotals[key]['MonthlyAverage'][month],
]
for year in all_years:
this_row.append(yearTotals[key][year][month])
writer.writerow(this_row)
return response
def get_form_kwargs(self, **kwargs):
'''
Get the list of recent months and recent series to pass to the form
'''
numMonths = 12
lastStart = Event.objects.annotate(Min('eventoccurrence__startTime')).order_by('-eventoccurrence__startTime__min').values_list('eventoccurrence__startTime__min',flat=True).first()
if lastStart:
month = lastStart.month
year = lastStart.year
else:
month = timezone.now().month
year = timezone.now().year
months = [('',_('None'))]
for i in range(0,numMonths):
newmonth = (month - i - 1) % 12 + 1
newyear = year
if month - i - 1 < 0:
newyear = year - 1
newdate = datetime(year=newyear,month=newmonth,day=1)
newdateStr = newdate.strftime("%m-%Y")
monthStr = newdate.strftime("%B, %Y")
months.append((newdateStr,monthStr))
cutoff = timezone.now() - timedelta(days=120)
allEvents = Event.objects.filter(startTime__gte=cutoff).order_by('-startTime')
kwargs = super(SendEmailView, self).get_form_kwargs(**kwargs)
kwargs.update({
"months": months,
"recentseries": [('','None')] + [(x.id,'%s %s: %s' % (month_name[x.month],x.year,x.name)) for x in allEvents],
"customers": self.customers,
})
return kwargs
def getMonthName(self):
'''
This exists as a separate method because sometimes events should really
belong to more than one month (e.g. class series that persist over multiple months).
'''
class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrence_set.all()])
multiclass_months = [x[0] for x in class_counter.items() if x[1] > 1]
all_months = [x[0] for x in class_counter.items()]
if multiclass_months:
multiclass_months.sort()
return '/'.join([month_name[x[1]] for x in multiclass_months])
else:
return month_name[min(all_months)[1]]
def url(self):
if self.status not in [self.RegStatus.hidden, self.RegStatus.linkOnly]:
return reverse('classView',args=[self.year,month_name[self.month or 0] or None,self.classDescription.slug])
def __str__(self):
if self.month and self.year and self.classDescription:
# In case of unsaved series, month and year are not yet set.
return month_name[self.month or 0] + ' ' + str(self.year) + ": " + self.classDescription.title
elif self.classDescription:
return str(_('Class Series: %s' % self.classDescription.title))
else:
return str(_('Class Series'))