]> git.openstreetmap.org Git - osqa.git/blob - forum/views/decorators.py
d86a62eee838e1d2bd639bb608a4168de6da124c
[osqa.git] / forum / views / decorators.py
1 from django.http import HttpResponse, HttpResponseRedirect, Http404\r
2 from django.utils import simplejson\r
3 from django.core.paginator import Paginator, EmptyPage\r
4 from django.shortcuts import render_to_response\r
5 from django.core.urlresolvers import reverse\r
6 from django.template import RequestContext\r
7 from django.utils.translation import ungettext, ugettext as _\r
8 from forum.modules import ui, decorate\r
9 import logging\r
10 \r
11 def render(template=None, tab=None, tab_title='', weight=500, tabbed=True):\r
12     def decorator(func):\r
13         def decorated(request, *args, **kwargs):\r
14             context = func(request, *args, **kwargs)\r
15 \r
16             if isinstance(context, HttpResponse):\r
17                 return context\r
18 \r
19             if tab is not None:\r
20                 context['tab'] = tab\r
21 \r
22             return render_to_response(context.pop('template', template), context,\r
23                                       context_instance=RequestContext(request))\r
24 \r
25         if tabbed and tab:\r
26             ui.register(ui.PAGE_TOP_TABS,\r
27                         ui.PageTab(tab, tab_title, lambda: reverse(func.__name__), weight=weight))\r
28             \r
29         return decorated\r
30 \r
31     return decorator\r
32 \r
33 class CommandException(Exception):\r
34     pass\r
35 \r
36 class RefreshPageCommand(HttpResponse):\r
37     def __init__(self):\r
38         super(RefreshPageCommand, self).__init__(\r
39                 content=simplejson.dumps({'commands': {'refresh_page': []}, 'success': True}),\r
40                 mimetype="application/json")\r
41 \r
42 def command(func, request, *args, **kwargs):\r
43     try:\r
44         response = func(request, *args, **kwargs)\r
45 \r
46         if isinstance(response, HttpResponse):\r
47             return response\r
48 \r
49         response['success'] = True\r
50     except Exception, e:\r
51         import traceback\r
52         #traceback.print_exc()\r
53 \r
54         if isinstance(e, CommandException):\r
55             response = {\r
56             'success': False,\r
57             'error_message': e.message\r
58             }\r
59         else:\r
60             logging.error("%s: %s" % (func.__name__, str(e)))\r
61             logging.error(traceback.format_exc())\r
62             response = {\r
63             'success': False,\r
64             'error_message': _("We're sorry, but an unknown error ocurred.<br />Please try again in a while.")\r
65             }\r
66 \r
67     if request.is_ajax():\r
68         return HttpResponse(simplejson.dumps(response), mimetype="application/json")\r
69     else:\r
70         return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\r
71 \r