]> git.openstreetmap.org Git - osqa.git/blob - forum/views/decorators.py
Some more fixes in the subscribe button.
[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(context, request, *args, **kwargs):\r
14             if isinstance(context, HttpResponse):\r
15                 return context\r
16 \r
17             if tab is not None:\r
18                 context['tab'] = tab\r
19 \r
20             return render_to_response(context.pop('template', template), context,\r
21                                       context_instance=RequestContext(request))\r
22 \r
23         if tabbed and tab and tab_title:\r
24             ui.register(ui.PAGE_TOP_TABS,\r
25                         ui.PageTab(tab, tab_title, lambda: reverse(func.__name__), weight=weight))\r
26             \r
27         return decorate.result.withfn(decorated, needs_params=True)(func)\r
28 \r
29     return decorator\r
30 \r
31 class CommandException(Exception):\r
32     pass\r
33 \r
34 class RefreshPageCommand(HttpResponse):\r
35     def __init__(self):\r
36         super(RefreshPageCommand, self).__init__(\r
37                 content=simplejson.dumps({'commands': {'refresh_page': []}, 'success': True}),\r
38                 mimetype="application/json")\r
39 \r
40 def command(func, request, *args, **kwargs):\r
41     try:\r
42         response = func(request, *args, **kwargs)\r
43 \r
44         if isinstance(response, HttpResponse):\r
45             return response\r
46 \r
47         response['success'] = True\r
48     except Exception, e:\r
49         import traceback\r
50         #traceback.print_exc()\r
51 \r
52         if isinstance(e, CommandException):\r
53             response = {\r
54             'success': False,\r
55             'error_message': e.message\r
56             }\r
57         else:\r
58             logging.error("%s: %s" % (func.__name__, str(e)))\r
59             logging.error(traceback.format_exc())\r
60             response = {\r
61             'success': False,\r
62             'error_message': _("We're sorry, but an unknown error ocurred.<br />Please try again in a while.")\r
63             }\r
64 \r
65     if request.is_ajax():\r
66         return HttpResponse(simplejson.dumps(response), mimetype="application/json")\r
67     else:\r
68         return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\r
69 \r