fixed widget colors
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import tempfile
6 import zipfile
7 import sys
8 import pprint
9 import traceback
10 import re
11 import itertools
12 from operator import itemgetter
13
14 from django.conf import settings
15 from django.template import RequestContext
16 from django.shortcuts import render_to_response, get_object_or_404
17 from django.http import HttpResponse, HttpResponseRedirect, Http404
18 from django.core.urlresolvers import reverse
19 from django.db.models import Q
20 from django.contrib.auth.decorators import login_required, user_passes_test
21 from django.utils.datastructures import SortedDict
22 from django.views.decorators.http import require_POST
23 from django.contrib import auth
24 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
25 from django.utils import simplejson
26 from django.utils.functional import Promise
27 from django.utils.encoding import force_unicode
28 from django.utils.http import urlquote_plus
29 from django.views.decorators import cache
30 from django.utils.translation import ugettext as _
31 from django.views.generic.list_detail import object_list
32
33 from catalogue import models
34 from catalogue import forms
35 from catalogue.utils import split_tags
36 from newtagging import views as newtagging_views
37
38
39 staff_required = user_passes_test(lambda user: user.is_staff)
40
41
42 class LazyEncoder(simplejson.JSONEncoder):
43     def default(self, obj):
44         if isinstance(obj, Promise):
45             return force_unicode(obj)
46         return obj
47
48 # shortcut for JSON reponses
49 class JSONResponse(HttpResponse):
50     def __init__(self, data={}, callback=None, **kwargs):
51         # get rid of mimetype
52         kwargs.pop('mimetype', None)
53         data = simplejson.dumps(data)
54         if callback:
55             data = callback + "(" + data + ");" 
56         super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
57
58
59 def main_page(request):
60     if request.user.is_authenticated():
61         shelves = models.Tag.objects.filter(category='set', user=request.user)
62         new_set_form = forms.NewSetForm()
63
64     tags = models.Tag.objects.exclude(category__in=('set', 'book'))
65     for tag in tags:
66         tag.count = tag.get_count()
67     categories = split_tags(tags)
68     fragment_tags = categories.get('theme', [])
69
70     form = forms.SearchForm()
71     return render_to_response('catalogue/main_page.html', locals(),
72         context_instance=RequestContext(request))
73
74
75 def book_list(request):
76     form = forms.SearchForm()
77
78     books_by_parent = {}
79     for book in models.Book.objects.all().order_by('parent_number'):
80         books_by_parent.setdefault(book.parent, []).append(book)
81
82     orphans = []
83     books_by_author = SortedDict()
84     for tag in models.Tag.objects.filter(category='author'):
85         books_by_author[tag] = []
86
87     for book in books_by_parent[None]:
88         authors = list(book.tags.filter(category='author'))
89         if authors:
90             for author in authors:
91                 books_by_author[author].append(book)
92         else:
93             orphans.append(book)
94
95     return render_to_response('catalogue/book_list.html', locals(),
96         context_instance=RequestContext(request))
97
98
99 def differentiate_tags(request, tags, ambiguous_slugs):
100     beginning = '/'.join(tag.url_chunk for tag in tags)
101     unparsed = '/'.join(ambiguous_slugs[1:])
102     options = []
103     for tag in models.Tag.objects.exclude(category='book').filter(slug=ambiguous_slugs[0]):
104         options.append({
105             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
106             'tags': [tag]
107         })
108     return render_to_response('catalogue/differentiate_tags.html',
109                 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
110                 context_instance=RequestContext(request))
111
112
113 def tagged_object_list(request, tags=''):
114     try:
115         tags = models.Tag.get_tag_list(tags)
116     except models.Tag.DoesNotExist:
117         raise Http404
118     except models.Tag.MultipleObjectsReturned, e:
119         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
120
121     try:
122         if len(tags) > settings.MAX_TAG_LIST:
123             raise Http404
124     except AttributeError:
125         pass
126
127     if len([tag for tag in tags if tag.category == 'book']):
128         raise Http404
129
130     theme_is_set = [tag for tag in tags if tag.category == 'theme']
131     shelf_is_set = [tag for tag in tags if tag.category == 'set']
132     only_shelf = shelf_is_set and len(tags) == 1
133     only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
134
135     objects = only_author = pd_counter = None
136     categories = {}
137
138     if theme_is_set:
139         shelf_tags = [tag for tag in tags if tag.category == 'set']
140         fragment_tags = [tag for tag in tags if tag.category != 'set']
141         fragments = models.Fragment.tagged.with_all(fragment_tags)
142
143         if shelf_tags:
144             books = models.Book.tagged.with_all(shelf_tags).order_by()
145             l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in books])
146             fragments = models.Fragment.tagged.with_any(l_tags, fragments)
147
148         # newtagging goes crazy if we just try:
149         #related_tags = models.Tag.objects.usage_for_queryset(fragments, counts=True,
150         #                    extra={'where': ["catalogue_tag.category != 'book'"]})
151         fragment_keys = [fragment.pk for fragment in fragments]
152         if fragment_keys:
153             related_tags = models.Fragment.tags.usage(counts=True,
154                                 filters={'pk__in': fragment_keys},
155                                 extra={'where': ["catalogue_tag.category != 'book'"]})
156             related_tags = (tag for tag in related_tags if tag not in fragment_tags)
157             categories = split_tags(related_tags)
158
159             objects = fragments
160     else:
161         # get relevant books and their tags
162         objects = models.Book.tagged.with_all(tags).order_by()
163         if not shelf_is_set:
164             # eliminate descendants
165             l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
166             descendants_keys = [book.pk for book in models.Book.tagged.with_any(l_tags)]
167             if descendants_keys:
168                 objects = objects.exclude(pk__in=descendants_keys)
169
170         # get related tags from `tag_counter` and `theme_counter`
171         related_counts = {}
172         tags_pks = [tag.pk for tag in tags]
173         for book in objects:
174             for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
175                 if tag_pk in tags_pks:
176                     continue
177                 related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
178         related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
179         related_tags = [tag for tag in related_tags if tag not in tags]
180         for tag in related_tags:
181             tag.count = related_counts[tag.pk]
182
183         categories = split_tags(related_tags)
184         del related_tags
185
186     if not objects:
187         only_author = len(tags) == 1 and tags[0].category == 'author'
188         pd_counter = only_author and tags[0].goes_to_pd()
189         objects = models.Book.objects.none()
190
191     return object_list(
192         request,
193         objects,
194         template_name='catalogue/tagged_object_list.html',
195         extra_context={
196             'categories': categories,
197             'only_shelf': only_shelf,
198             'only_author': only_author,
199             'pd_counter': pd_counter,
200             'only_my_shelf': only_my_shelf,
201             'formats_form': forms.DownloadFormatsForm(),
202
203             'tags': tags,
204         }
205     )
206
207
208 def book_fragments(request, book_slug, theme_slug):
209     book = get_object_or_404(models.Book, slug=book_slug)
210     book_tag = get_object_or_404(models.Tag, slug='l-' + book_slug, category='book')
211     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
212     fragments = models.Fragment.tagged.with_all([book_tag, theme])
213
214     form = forms.SearchForm()
215     return render_to_response('catalogue/book_fragments.html', locals(),
216         context_instance=RequestContext(request))
217
218
219 def book_detail(request, slug):
220     try:
221         book = models.Book.objects.get(slug=slug)
222     except models.Book.DoesNotExist:
223         return book_stub_detail(request, slug)
224
225     book_tag = book.book_tag()
226     tags = list(book.tags.filter(~Q(category='set')))
227     categories = split_tags(tags)
228     book_children = book.children.all().order_by('parent_number')
229     
230     _book = book
231     parents = []
232     while _book.parent:
233         parents.append(_book.parent)
234         _book = _book.parent
235     parents = reversed(parents)
236
237     theme_counter = book.theme_counter
238     book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
239     for tag in book_themes:
240         tag.count = theme_counter[tag.pk]
241
242     extra_info = book.get_extra_info_value()
243
244     form = forms.SearchForm()
245     return render_to_response('catalogue/book_detail.html', locals(),
246         context_instance=RequestContext(request))
247
248
249 def book_stub_detail(request, slug):
250     book = get_object_or_404(models.BookStub, slug=slug)
251     pd_counter = book.pd
252     form = forms.SearchForm()
253
254     return render_to_response('catalogue/book_stub_detail.html', locals(),
255         context_instance=RequestContext(request))
256
257
258 def book_text(request, slug):
259     book = get_object_or_404(models.Book, slug=slug)
260     if not book.has_html_file():
261         raise Http404
262     book_themes = {}
263     for fragment in book.fragments.all():
264         for theme in fragment.tags.filter(category='theme'):
265             book_themes.setdefault(theme, []).append(fragment)
266
267     book_themes = book_themes.items()
268     book_themes.sort(key=lambda s: s[0].sort_key)
269     return render_to_response('catalogue/book_text.html', locals(),
270         context_instance=RequestContext(request))
271
272
273 # ==========
274 # = Search =
275 # ==========
276
277 def _no_diacritics_regexp(query):
278     """ returns a regexp for searching for a query without diacritics
279
280     should be locale-aware """
281     names = {
282         u'a':u'aąĄ', u'c':u'cćĆ', u'e':u'eęĘ', u'l': u'lłŁ', u'n':u'nńŃ', u'o':u'oóÓ', u's':u'sśŚ', u'z':u'zźżŹŻ',
283         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
284         }
285     def repl(m):
286         l = m.group()
287         return u"(%s)" % '|'.join(names[l])
288     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
289
290 def unicode_re_escape(query):
291     """ Unicode-friendly version of re.escape """
292     return re.sub('(?u)(\W)', r'\\\1', query)
293
294 def _word_starts_with(name, prefix):
295     """returns a Q object getting models having `name` contain a word
296     starting with `prefix`
297
298     We define word characters as alphanumeric and underscore, like in JS.
299
300     Works for MySQL, PostgreSQL, Oracle.
301     For SQLite, _sqlite* version is substituted for this.
302     """
303     kwargs = {}
304
305     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
306     # can't use [[:<:]] (word start),
307     # but we want both `xy` and `(xy` to catch `(xyz)`
308     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
309
310     return Q(**kwargs)
311
312
313 def _sqlite_word_starts_with(name, prefix):
314     """ version of _word_starts_with for SQLite
315
316     SQLite in Django uses Python re module
317     """
318     kwargs = {}
319     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
320     kwargs['%s__iregex' % name] = ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
321     return Q(**kwargs)
322
323
324 if settings.DATABASE_ENGINE == 'sqlite3':
325     _word_starts_with = _sqlite_word_starts_with
326
327
328 def _tags_starting_with(prefix, user=None):
329     prefix = prefix.lower()
330     book_stubs = models.BookStub.objects.filter(_word_starts_with('title', prefix))
331     books = models.Book.objects.filter(_word_starts_with('title', prefix))
332     book_stubs = filter(lambda x: x not in books, book_stubs)
333     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
334     if user and user.is_authenticated():
335         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
336     else:
337         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
338     return list(books) + list(tags) + list(book_stubs)
339
340
341 def _get_result_link(match, tag_list):
342     if isinstance(match, models.Book) or isinstance(match, models.BookStub):
343         return match.get_absolute_url()
344     else:
345         return reverse('catalogue.views.tagged_object_list',
346             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
347         )
348
349 def _get_result_type(match):
350     if isinstance(match, models.Book) or isinstance(match, models.BookStub):
351         type = 'book'
352     else:
353         type = match.category
354     return type
355
356
357
358 def find_best_matches(query, user=None):
359     """ Finds a Book, Tag or Bookstub best matching a query.
360
361     Returns a with:
362       - zero elements when nothing is found,
363       - one element when a best result is found,
364       - more then one element on multiple exact matches
365
366     Raises a ValueError on too short a query.
367     """
368
369     query = query.lower()
370     if len(query) < 2:
371         raise ValueError("query must have at least two characters")
372
373     result = tuple(_tags_starting_with(query, user))
374     exact_matches = tuple(res for res in result if res.name.lower() == query)
375     if exact_matches:
376         return exact_matches
377     else:
378         return result[:1]
379
380
381 def search(request):
382     tags = request.GET.get('tags', '')
383     prefix = request.GET.get('q', '')
384
385     try:
386         tag_list = models.Tag.get_tag_list(tags)
387     except:
388         tag_list = []
389
390     try:
391         result = find_best_matches(prefix, request.user)
392     except ValueError:
393         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
394             context_instance=RequestContext(request))
395
396     if len(result) == 1:
397         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
398     elif len(result) > 1:
399         return render_to_response('catalogue/search_multiple_hits.html',
400             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
401             context_instance=RequestContext(request))
402     else:
403         return render_to_response('catalogue/search_no_hits.html', {'tags':tag_list, 'prefix':prefix},
404             context_instance=RequestContext(request))
405
406
407 def tags_starting_with(request):
408     prefix = request.GET.get('q', '')
409     # Prefix must have at least 2 characters
410     if len(prefix) < 2:
411         return HttpResponse('')
412     tags_list = []
413     result = ""   
414     for tag in _tags_starting_with(prefix, request.user):
415         if not tag.name in tags_list:
416             result += "\n" + tag.name
417             tags_list.append(tag.name)
418     return HttpResponse(result)
419
420 def json_tags_starting_with(request, callback=None):
421     # Callback for JSONP
422     prefix = request.GET.get('q', '')
423     callback = request.GET.get('callback', '')
424     # Prefix must have at least 2 characters
425     if len(prefix) < 2:
426         return HttpResponse('')
427     tags_list = []
428     result = ""   
429     for tag in _tags_starting_with(prefix, request.user):
430         if not tag.name in tags_list:
431             result += "\n" + tag.name
432             tags_list.append(tag.name)
433     dict_result = {"matches": tags_list}
434     return JSONResponse(dict_result, callback)
435
436 # ====================
437 # = Shelf management =
438 # ====================
439 @login_required
440 @cache.never_cache
441 def user_shelves(request):
442     shelves = models.Tag.objects.filter(category='set', user=request.user)
443     new_set_form = forms.NewSetForm()
444     return render_to_response('catalogue/user_shelves.html', locals(),
445             context_instance=RequestContext(request))
446
447 @cache.never_cache
448 def book_sets(request, slug):
449     book = get_object_or_404(models.Book, slug=slug)
450     user_sets = models.Tag.objects.filter(category='set', user=request.user)
451     book_sets = book.tags.filter(category='set', user=request.user)
452
453     if not request.user.is_authenticated():
454         return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
455
456     if request.method == 'POST':
457         form = forms.ObjectSetsForm(book, request.user, request.POST)
458         if form.is_valid():
459             old_shelves = list(book.tags.filter(category='set'))
460             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
461
462             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
463                 shelf.book_count = None
464                 shelf.save()
465
466             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
467                 shelf.book_count = None
468                 shelf.save()
469
470             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
471             if request.is_ajax():
472                 return HttpResponse(_('<p>Shelves were sucessfully saved.</p>'))
473             else:
474                 return HttpResponseRedirect('/')
475     else:
476         form = forms.ObjectSetsForm(book, request.user)
477         new_set_form = forms.NewSetForm()
478
479     return render_to_response('catalogue/book_sets.html', locals(),
480         context_instance=RequestContext(request))
481
482
483 @login_required
484 @require_POST
485 @cache.never_cache
486 def remove_from_shelf(request, shelf, book):
487     book = get_object_or_404(models.Book, slug=book)
488     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
489
490     if shelf in book.tags:
491         models.Tag.objects.remove_tag(book, shelf)
492
493         shelf.book_count = None
494         shelf.save()
495
496         return HttpResponse(_('Book was successfully removed from the shelf'))
497     else:
498         return HttpResponse(_('This book is not on the shelf'))
499
500
501 def collect_books(books):
502     """
503     Returns all real books in collection.
504     """
505     result = []
506     for book in books:
507         if len(book.children.all()) == 0:
508             result.append(book)
509         else:
510             result += collect_books(book.children.all())
511     return result
512
513
514 @cache.never_cache
515 def download_shelf(request, slug):
516     """"
517     Create a ZIP archive on disk and transmit it in chunks of 8KB,
518     without loading the whole file into memory. A similar approach can
519     be used for large dynamic PDF files.
520     """
521     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
522
523     formats = []
524     form = forms.DownloadFormatsForm(request.GET)
525     if form.is_valid():
526         formats = form.cleaned_data['formats']
527     if len(formats) == 0:
528         formats = ['pdf', 'epub', 'odt', 'txt', 'mp3', 'ogg']
529
530     # Create a ZIP archive
531     temp = tempfile.TemporaryFile()
532     archive = zipfile.ZipFile(temp, 'w')
533
534     already = set()
535     for book in collect_books(models.Book.tagged.with_all(shelf)):
536         if 'pdf' in formats and book.pdf_file:
537             filename = book.pdf_file.path
538             archive.write(filename, str('%s.pdf' % book.slug))
539         if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
540             filename = book.root_ancestor.epub_file.path
541             archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
542             already.add(book.root_ancestor)
543         if 'odt' in formats and book.odt_file:
544             filename = book.odt_file.path
545             archive.write(filename, str('%s.odt' % book.slug))
546         if 'txt' in formats and book.txt_file:
547             filename = book.txt_file.path
548             archive.write(filename, str('%s.txt' % book.slug))
549         if 'mp3' in formats and book.mp3_file:
550             filename = book.mp3_file.path
551             archive.write(filename, str('%s.mp3' % book.slug))
552         if 'ogg' in formats and book.ogg_file:
553             filename = book.ogg_file.path
554             archive.write(filename, str('%s.ogg' % book.slug))
555     archive.close()
556
557     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
558     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
559     response['Content-Length'] = temp.tell()
560
561     temp.seek(0)
562     response.write(temp.read())
563     return response
564
565
566 @cache.never_cache
567 def shelf_book_formats(request, shelf):
568     """"
569     Returns a list of formats of books in shelf.
570     """
571     shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
572
573     formats = {'pdf': False, 'epub': False, 'odt': False, 'txt': False, 'mp3': False, 'ogg': False}
574
575     for book in collect_books(models.Book.tagged.with_all(shelf)):
576         if book.pdf_file:
577             formats['pdf'] = True
578         if book.root_ancestor.epub_file:
579             formats['epub'] = True
580         if book.odt_file:
581             formats['odt'] = True
582         if book.txt_file:
583             formats['txt'] = True
584         if book.mp3_file:
585             formats['mp3'] = True
586         if book.ogg_file:
587             formats['ogg'] = True
588
589     return HttpResponse(LazyEncoder().encode(formats))
590
591
592 @login_required
593 @require_POST
594 @cache.never_cache
595 def new_set(request):
596     new_set_form = forms.NewSetForm(request.POST)
597     if new_set_form.is_valid():
598         new_set = new_set_form.save(request.user)
599
600         if request.is_ajax():
601             return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully created</p>') % new_set)
602         else:
603             return HttpResponseRedirect('/')
604
605     return HttpResponseRedirect('/')
606
607
608 @login_required
609 @require_POST
610 @cache.never_cache
611 def delete_shelf(request, slug):
612     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
613     user_set.delete()
614
615     if request.is_ajax():
616         return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
617     else:
618         return HttpResponseRedirect('/')
619
620
621 # ==================
622 # = Authentication =
623 # ==================
624 @require_POST
625 @cache.never_cache
626 def login(request):
627     form = AuthenticationForm(data=request.POST, prefix='login')
628     if form.is_valid():
629         auth.login(request, form.get_user())
630         response_data = {'success': True, 'errors': {}}
631     else:
632         response_data = {'success': False, 'errors': form.errors}
633     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
634
635
636 @require_POST
637 @cache.never_cache
638 def register(request):
639     registration_form = UserCreationForm(request.POST, prefix='registration')
640     if registration_form.is_valid():
641         user = registration_form.save()
642         user = auth.authenticate(
643             username=registration_form.cleaned_data['username'],
644             password=registration_form.cleaned_data['password1']
645         )
646         auth.login(request, user)
647         response_data = {'success': True, 'errors': {}}
648     else:
649         response_data = {'success': False, 'errors': registration_form.errors}
650     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
651
652
653 @cache.never_cache
654 def logout_then_redirect(request):
655     auth.logout(request)
656     return HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
657
658
659
660 # =========
661 # = Admin =
662 # =========
663 @login_required
664 @staff_required
665 def import_book(request):
666     """docstring for import_book"""
667     book_import_form = forms.BookImportForm(request.POST, request.FILES)
668     if book_import_form.is_valid():
669         try:
670             book_import_form.save()
671         except:
672             info = sys.exc_info()
673             exception = pprint.pformat(info[1])
674             tb = '\n'.join(traceback.format_tb(info[2]))
675             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
676         return HttpResponse(_("Book imported successfully"))
677     else:
678         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
679
680
681
682 def clock(request):
683     """ Provides server time for jquery.countdown,
684     in a format suitable for Date.parse()
685     """
686     from datetime import datetime
687     return HttpResponse(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))