Code

Ticket #608: django-update.diff

File django-update.diff, 21.1 KB (added by scaba, 9 years ago)
Line 
1Index: django/views/generic/date_based.py
2===================================================================
3--- django/views/generic/date_based.py  (revision 827)
4+++ django/views/generic/date_based.py  (working copy)
5@@ -1,258 +1,301 @@
6-from django.core import template_loader
7-from django.core.exceptions import Http404, ObjectDoesNotExist
8-from django.core.extensions import DjangoContext as Context
9-from django.core.xheaders import populate_xheaders
10-from django.models import get_module
11-from django.utils.httpwrappers import HttpResponse
12-import datetime, time
13-
14-def archive_index(request, app_label, module_name, date_field, num_latest=15,
15-                  template_name=None, template_loader=template_loader,
16-                  extra_lookup_kwargs={}, extra_context={}):
17-    """
18-    Generic top-level archive of date-based objects.
19-
20-    Templates: ``<app_label>/<module_name>_archive``
21-    Context:
22-        date_list
23-            List of years
24-        latest
25-            Latest N (defaults to 15) objects by date
26-    """
27-    mod = get_module(app_label, module_name)
28-    lookup_kwargs = {'%s__lte' % date_field: datetime.datetime.now()}
29-    lookup_kwargs.update(extra_lookup_kwargs)
30-    date_list = getattr(mod, "get_%s_list" % date_field)('year', **lookup_kwargs)[::-1]
31-    if not date_list:
32-        raise Http404("No %s.%s available" % (app_label, module_name))
33-
34-    if num_latest:
35-        lookup_kwargs.update({
36-            'limit': num_latest,
37-            'order_by': ('-' + date_field,),
38-        })
39-        latest = mod.get_list(**lookup_kwargs)
40-    else:
41-        latest = None
42-
43-    if not template_name:
44-        template_name = "%s/%s_archive" % (app_label, module_name)
45-    t = template_loader.get_template(template_name)
46-    c = Context(request, {
47-        'date_list' : date_list,
48-        'latest' : latest,
49-    })
50-    for key, value in extra_context.items():
51-        if callable(value):
52-            c[key] = value()
53-        else:
54-            c[key] = value
55-    return HttpResponse(t.render(c))
56-
57-def archive_year(request, year, app_label, module_name, date_field,
58-                 template_name=None, template_loader=template_loader,
59-                 extra_lookup_kwargs={}, extra_context={}):
60-    """
61-    Generic yearly archive view.
62-
63-    Templates: ``<app_label>/<module_name>_archive_year``
64-    Context:
65-        date_list
66-            List of months in this year with objects
67-        year
68-            This year
69-    """
70-    mod = get_module(app_label, module_name)
71-    now = datetime.datetime.now()
72-    lookup_kwargs = {'%s__year' % date_field: year}
73-    # Only bother to check current date if the year isn't in the past.
74-    if int(year) >= now.year:
75-        lookup_kwargs['%s__lte' % date_field] = now
76-    lookup_kwargs.update(extra_lookup_kwargs)
77-    date_list = getattr(mod, "get_%s_list" % date_field)('month', **lookup_kwargs)
78-    if not date_list:
79-        raise Http404
80-    if not template_name:
81-        template_name = "%s/%s_archive_year" % (app_label, module_name)
82-    t = template_loader.get_template(template_name)
83-    c = Context(request, {
84-        'date_list': date_list,
85-        'year': year,
86-    })
87-    for key, value in extra_context.items():
88-        if callable(value):
89-            c[key] = value()
90-        else:
91-            c[key] = value
92-    return HttpResponse(t.render(c))
93-
94-def archive_month(request, year, month, app_label, module_name, date_field,
95-                  month_format='%b', template_name=None, template_loader=template_loader,
96-                  extra_lookup_kwargs={}, extra_context={}):
97-    """
98-    Generic monthly archive view.
99-
100-    Templates: ``<app_label>/<module_name>_archive_month``
101-    Context:
102-        month:
103-            this month
104-        object_list:
105-            list of objects published in the given month
106-    """
107-    try:
108-        date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
109-    except ValueError:
110-        raise Http404
111-
112-    mod = get_module(app_label, module_name)
113-    now = datetime.datetime.now()
114-    # Calculate first and last day of month, for use in a date-range lookup.
115-    first_day = date.replace(day=1)
116-    last_day = date
117-    for i in (31, 30, 29, 28):
118-        try:
119-            last_day = last_day.replace(day=i)
120-        except ValueError:
121-            continue
122-        else:
123-            break
124-    lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)}
125-    # Only bother to check current date if the month isn't in the past.
126-    if last_day >= now.date():
127-        lookup_kwargs['%s__lte' % date_field] = now
128-    lookup_kwargs.update(extra_lookup_kwargs)
129-    object_list = mod.get_list(**lookup_kwargs)
130-    if not object_list:
131-        raise Http404
132-    if not template_name:
133-        template_name = "%s/%s_archive_month" % (app_label, module_name)
134-    t = template_loader.get_template(template_name)
135-    c = Context(request, {
136-        'object_list': object_list,
137-        'month': date,
138-    })
139-    for key, value in extra_context.items():
140-        if callable(value):
141-            c[key] = value()
142-        else:
143-            c[key] = value
144-    return HttpResponse(t.render(c))
145-
146-def archive_day(request, year, month, day, app_label, module_name, date_field,
147-                month_format='%b', day_format='%d', template_name=None,
148-                template_loader=template_loader, extra_lookup_kwargs={},
149-                extra_context={}, allow_empty=False):
150-    """
151-    Generic daily archive view.
152-
153-    Templates: ``<app_label>/<module_name>_archive_day``
154-    Context:
155-        object_list:
156-            list of objects published that day
157-        day:
158-            (datetime) the day
159-        previous_day
160-            (datetime) the previous day
161-        next_day
162-            (datetime) the next day, or None if the current day is today
163-    """
164-    try:
165-        date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
166-    except ValueError:
167-        raise Http404
168-
169-    mod = get_module(app_label, module_name)
170-    now = datetime.datetime.now()
171-    lookup_kwargs = {
172-        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
173-    }
174-    # Only bother to check current date if the date isn't in the past.
175-    if date >= now.date():
176-        lookup_kwargs['%s__lte' % date_field] = now
177-    lookup_kwargs.update(extra_lookup_kwargs)
178-    object_list = mod.get_list(**lookup_kwargs)
179-    if not allow_empty and not object_list:
180-        raise Http404
181-    if not template_name:
182-        template_name = "%s/%s_archive_day" % (app_label, module_name)
183-    t = template_loader.get_template(template_name)
184-    c = Context(request, {
185-        'object_list': object_list,
186-        'day': date,
187-        'previous_day': date - datetime.timedelta(days=1),
188-        'next_day': (date < datetime.date.today()) and (date + datetime.timedelta(days=1)) or None,
189-    })
190-    for key, value in extra_context.items():
191-        if callable(value):
192-            c[key] = value()
193-        else:
194-            c[key] = value
195-    return HttpResponse(t.render(c))
196-
197-def archive_today(request, **kwargs):
198-    """
199-    Generic daily archive view for today. Same as archive_day view.
200-    """
201-    today = datetime.date.today()
202-    kwargs.update({
203-        'year': str(today.year),
204-        'month': today.strftime('%b').lower(),
205-        'day': str(today.day),
206-    })
207-    return archive_day(request, **kwargs)
208-
209-def object_detail(request, year, month, day, app_label, module_name, date_field,
210-                  month_format='%b', day_format='%d', object_id=None, slug=None,
211-                  slug_field=None, template_name=None, template_name_field=None,
212-                  template_loader=template_loader, extra_lookup_kwargs={},
213-                  extra_context={}):
214-    """
215-    Generic detail view from year/month/day/slug or year/month/day/id structure.
216-
217-    Templates: ``<app_label>/<module_name>_detail``
218-    Context:
219-        object:
220-            the object to be detailed
221-    """
222-    try:
223-        date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
224-    except ValueError:
225-        raise Http404
226-
227-    mod = get_module(app_label, module_name)
228-    now = datetime.datetime.now()
229-    lookup_kwargs = {
230-        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
231-    }
232-    # Only bother to check current date if the date isn't in the past.
233-    if date >= now.date():
234-        lookup_kwargs['%s__lte' % date_field] = now
235-    if object_id:
236-        lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
237-    elif slug and slug_field:
238-        lookup_kwargs['%s__exact' % slug_field] = slug
239-    else:
240-        raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield")
241-    lookup_kwargs.update(extra_lookup_kwargs)
242-    try:
243-        object = mod.get_object(**lookup_kwargs)
244-    except ObjectDoesNotExist:
245-        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
246-    if not template_name:
247-        template_name = "%s/%s_detail" % (app_label, module_name)
248-    if template_name_field:
249-        template_name_list = [getattr(object, template_name_field), template_name]
250-        t = template_loader.select_template(template_name_list)
251-    else:
252-        t = template_loader.get_template(template_name)
253-    c = Context(request, {
254-        'object': object,
255-    })
256-    for key, value in extra_context.items():
257-        if callable(value):
258-            c[key] = value()
259-        else:
260-            c[key] = value
261-    response = HttpResponse(t.render(c))
262-    populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
263-    return response
264+from django.core import template_loader
265+from django.core.exceptions import Http404, ObjectDoesNotExist
266+from django.core.extensions import DjangoContext as Context
267+from django.core.xheaders import populate_xheaders
268+from django.models import get_module
269+from django.utils.httpwrappers import HttpResponse
270+import datetime, time
271+
272+def archive_index(request, app_label, module_name, date_field, num_latest=15,
273+                  template_name=None, template_loader=template_loader,
274+                  extra_lookup_kwargs={}, extra_context={}):
275+    """
276+    Generic top-level archive of date-based objects.
277+
278+    Templates: ``<app_label>/<module_name>_archive``
279+    Context:
280+        date_list
281+            List of years
282+        latest
283+            Latest N (defaults to 15) objects by date
284+    """
285+    mod = get_module(app_label, module_name)
286+    lookup_kwargs = {'%s__lte' % date_field: datetime.datetime.now()}
287+    lookup_kwargs.update(extra_lookup_kwargs)
288+    date_list = getattr(mod, "get_%s_list" % date_field)('year', **lookup_kwargs)[::-1]
289+    if not date_list:
290+        raise Http404("No %s.%s available" % (app_label, module_name))
291+
292+    if num_latest:
293+        lookup_kwargs.update({
294+            'limit': num_latest,
295+            'order_by': ('-' + date_field,),
296+        })
297+        latest = mod.get_list(**lookup_kwargs)
298+    else:
299+        latest = None
300+
301+    if not template_name:
302+        template_name = "%s/%s_archive" % (app_label, module_name)
303+    t = template_loader.get_template(template_name)
304+    c = Context(request, {
305+        'date_list' : date_list,
306+        'latest' : latest,
307+    })
308+    for key, value in extra_context.items():
309+        if callable(value):
310+            c[key] = value()
311+        else:
312+            c[key] = value
313+    return HttpResponse(t.render(c))
314+
315+def archive_year(request, year, app_label, module_name, date_field, future_ok=False,
316+                 template_name=None, template_loader=template_loader,
317+                 extra_lookup_kwargs={}, extra_context={}):
318+    """
319+    Generic yearly archive view.
320+
321+    Templates: ``<app_label>/<module_name>_archive_year``
322+    Context:
323+        date_list
324+            List of months in this year with objects
325+        year
326+            This year
327+    """
328+    mod = get_module(app_label, module_name)
329+    now = datetime.datetime.now()
330+    lookup_kwargs = {'%s__year' % date_field: year}
331+    # Only bother to check current date if the year isn't in the past.
332+    if int(year) >= now.year and not future_ok:
333+        lookup_kwargs['%s__lte' % date_field] = now
334+    lookup_kwargs.update(extra_lookup_kwargs)
335+    date_list = getattr(mod, "get_%s_list" % date_field)('month', **lookup_kwargs)
336+    if not date_list:
337+        raise Http404
338+    if not template_name:
339+        template_name = "%s/%s_archive_year" % (app_label, module_name)
340+    t = template_loader.get_template(template_name)
341+    c = Context(request, {
342+        'date_list': date_list,
343+        'year': year,
344+    })
345+    for key, value in extra_context.items():
346+        if callable(value):
347+            c[key] = value()
348+        else:
349+            c[key] = value
350+    return HttpResponse(t.render(c))
351+
352+def archive_month(request, year, month, app_label, module_name, date_field,
353+                  month_format='%b', future_ok=False, template_name=None, template_loader=template_loader,
354+                  extra_lookup_kwargs={}, extra_context={}):
355+    """
356+    Generic monthly archive view.
357+
358+    Templates: ``<app_label>/<module_name>_archive_month``
359+    Context:
360+        month:
361+            this month
362+        object_list:
363+            list of objects published in the given month
364+    """
365+    try:
366+        date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
367+    except ValueError:
368+        raise Http404
369+
370+    mod = get_module(app_label, module_name)
371+    now = datetime.datetime.now()
372+    # Calculate first and last day of month, for use in a date-range lookup.
373+    first_day = date.replace(day=1)
374+    last_day = date
375+    for i in (31, 30, 29, 28):
376+        try:
377+            last_day = last_day.replace(day=i)
378+        except ValueError:
379+            continue
380+        else:
381+            break
382+    lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)}
383+    # Only bother to check current date if the month isn't in the past.
384+    if last_day >= now.date() and not future_ok:
385+        lookup_kwargs['%s__lte' % date_field] = now
386+    lookup_kwargs.update(extra_lookup_kwargs)
387+    object_list = mod.get_list(**lookup_kwargs)
388+    if not object_list:
389+        raise Http404
390+    if not template_name:
391+        template_name = "%s/%s_archive_month" % (app_label, module_name)
392+    t = template_loader.get_template(template_name)
393+    c = Context(request, {
394+        'object_list': object_list,
395+        'month': date,
396+    })
397+    for key, value in extra_context.items():
398+        if callable(value):
399+            c[key] = value()
400+        else:
401+            c[key] = value
402+    return HttpResponse(t.render(c))
403+
404+def archive_day(request, year, month, day, app_label, module_name, date_field,
405+                month_format='%b', day_format='%d', future_ok=False, template_name=None,
406+                template_loader=template_loader, extra_lookup_kwargs={},
407+                extra_context={}, allow_empty=False):
408+    """
409+    Generic daily archive view.
410+
411+    Templates: ``<app_label>/<module_name>_archive_day``
412+    Context:
413+        object_list:
414+            list of objects published that day
415+        day:
416+            (datetime) the day
417+        previous_day
418+            (datetime) the previous day
419+        next_day
420+            (datetime) the next day, or None if the current day is today
421+    """
422+    try:
423+        date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
424+    except ValueError:
425+        raise Http404
426+
427+    mod = get_module(app_label, module_name)
428+    now = datetime.datetime.now()
429+    lookup_kwargs = {
430+        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
431+    }
432+    # Only bother to check current date if the date isn't in the past.
433+    if date >= now.date() and not future_ok:
434+        lookup_kwargs['%s__lte' % date_field] = now
435+    lookup_kwargs.update(extra_lookup_kwargs)
436+    object_list = mod.get_list(**lookup_kwargs)
437+    if not allow_empty and not object_list:
438+        raise Http404
439+    if not template_name:
440+        template_name = "%s/%s_archive_day" % (app_label, module_name)
441+    t = template_loader.get_template(template_name)
442+    c = Context(request, {
443+        'object_list': object_list,
444+        'day': date,
445+        'previous_day': date - datetime.timedelta(days=1),
446+        'next_day': (date < datetime.date.today()) and (date + datetime.timedelta(days=1)) or None,
447+    })
448+    for key, value in extra_context.items():
449+        if callable(value):
450+            c[key] = value()
451+        else:
452+            c[key] = value
453+    return HttpResponse(t.render(c))
454+
455+def archive_today(request, **kwargs):
456+    """
457+    Generic daily archive view for today. Same as archive_day view.
458+    """
459+    today = datetime.date.today()
460+    kwargs.update({
461+        'year': str(today.year),
462+        'month': today.strftime('%b').lower(),
463+        'day': str(today.day),
464+    })
465+    return archive_day(request, **kwargs)
466+
467+def object_detail(request, year, month, day, app_label, module_name, date_field,
468+                  month_format='%b', day_format='%d', object_id=None, slug=None,
469+                  slug_field=None, future_ok=False, template_name=None, template_name_field=None,
470+                  template_loader=template_loader, extra_lookup_kwargs={},
471+                  extra_context={}):
472+    """
473+    Generic detail view from year/month/day/slug or year/month/day/id structure.
474+
475+    Templates: ``<app_label>/<module_name>_detail``
476+    Context:
477+        object:
478+            the object to be detailed
479+    """
480+    try:
481+        date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
482+    except ValueError:
483+        raise Http404
484+
485+    mod = get_module(app_label, module_name)
486+    now = datetime.datetime.now()
487+    lookup_kwargs = {
488+        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
489+    }
490+    # Only bother to check current date if the date isn't in the past.
491+    if date >= now.date() and not future_ok:
492+        lookup_kwargs['%s__lte' % date_field] = now
493+    if object_id:
494+        lookup_kwargs['%s__exact' % mod.Klass._meta.pk.name] = object_id
495+    elif slug and slug_field:
496+        lookup_kwargs['%s__exact' % slug_field] = slug
497+    else:
498+        raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield")
499+    lookup_kwargs.update(extra_lookup_kwargs)
500+    try:
501+        object = mod.get_object(**lookup_kwargs)
502+    except ObjectDoesNotExist:
503+        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
504+    if not template_name:
505+        template_name = "%s/%s_detail" % (app_label, module_name)
506+    if template_name_field:
507+        template_name_list = [getattr(object, template_name_field), template_name]
508+        t = template_loader.select_template(template_name_list)
509+    else:
510+        t = template_loader.get_template(template_name)
511+    c = Context(request, {
512+        'object': object,
513+    })
514+    for key, value in extra_context.items():
515+        if callable(value):
516+            c[key] = value()
517+        else:
518+            c[key] = value
519+    response = HttpResponse(t.render(c))
520+    populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
521+    return response
522+
523+def upcoming_index(request, app_label, module_name, date_field, num_upcoming=15,
524+                  template_name=None, template_loader=template_loader,
525+                  extra_lookup_kwargs={}, extra_context={}):
526+    """
527+    Index of future/upcoming date-based objects.
528+
529+    Templates: ``<app_label>/<module_name>_upcoming``
530+    Context:
531+        date_list
532+            List of years
533+        upcoming
534+            Next N (defaults to 15) upcoming objects by date
535+    """
536+    mod = get_module(app_label, module_name)
537+    lookup_kwargs = {'%s__gte' % date_field: datetime.datetime.now()}
538+    lookup_kwargs.update(extra_lookup_kwargs)
539+    date_list = getattr(mod, "get_%s_list" % date_field)('year', **lookup_kwargs)[::-1]
540+    if not date_list:
541+        raise Http404("No %s.%s available" % (app_label, module_name))
542+
543+    if num_upcoming:
544+        lookup_kwargs.update({
545+            'limit': num_upcoming,
546+            'order_by': (date_field,),
547+        })
548+        upcoming = mod.get_list(**lookup_kwargs)
549+    else:
550+        upcoming = None
551+
552+    if not template_name:
553+        template_name = "%s/%s_upcoming" % (app_label, module_name)
554+    t = template_loader.get_template(template_name)
555+    c = Context(request, {
556+        'date_list' : date_list,
557+        'upcoming' : upcoming,
558+    })
559+    for key, value in extra_context.items():
560+        if callable(value):
561+            c[key] = value()
562+        else:
563+            c[key] = value
564+    return HttpResponse(t.render(c))