]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/books/views.py
35e9f0fe6096e7f7c76ad8fbafba69315ac41a1a
[osqa.git] / forum_modules / books / views.py
1 from django.shortcuts import render_to_response, get_object_or_404
2 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, Http404
3 from django.template import RequestContext
4 from django.contrib.auth.decorators import login_required
5 from django.core.urlresolvers import reverse
6 from django.utils.html import *
7
8 from models import *
9
10 from forum.forms import AskForm
11 from forum.views.readers import _get_tags_cache_json
12 from forum.models import *
13 from forum.utils.html import sanitize_html
14
15 def books(request):
16     return HttpResponseRedirect(reverse('books') + '/mysql-zhaoyang')
17
18 def book(request, short_name, unanswered=False):
19     """
20     1. questions list
21     2. book info
22     3. author info and blog rss items
23     """
24     """
25     List of Questions, Tagged questions, and Unanswered questions.
26     """
27     books = Book.objects.extra(where=['short_name = %s'], params=[short_name])
28     match_count = len(books)
29     if match_count == 0:
30         raise Http404
31     else:
32         # the book info
33         book = books[0]
34         # get author info
35         author_info = BookAuthorInfo.objects.get(book=book)
36         # get author rss info
37         author_rss = BookAuthorRss.objects.filter(book=book)
38
39         # get pagesize from session, if failed then get default value
40         user_page_size = request.session.get("pagesize", QUESTIONS_PAGE_SIZE)
41         # set pagesize equal to logon user specified value in database
42         if request.user.is_authenticated() and request.user.questions_per_page > 0:
43             user_page_size = request.user.questions_per_page
44
45         try:
46             page = int(request.GET.get('page', '1'))
47         except ValueError:
48             page = 1
49
50         view_id = request.GET.get('sort', None)
51         view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-answer_count", "mostvoted":"-score" }
52         try:
53             orderby = view_dic[view_id]
54         except KeyError:
55             view_id = "latest"
56             orderby = "-added_at"
57
58         # check if request is from tagged questions
59         if unanswered:
60             # check if request is from unanswered questions
61             # Article.objects.filter(publications__id__exact=1)
62             objects = Question.objects.filter(book__id__exact=book.id, deleted=False, answer_count=0).order_by(orderby)
63         else:
64             objects = Question.objects.filter(book__id__exact=book.id, deleted=False).order_by(orderby)
65
66         # RISK - inner join queries
67         objects = objects.select_related();
68         objects_list = Paginator(objects, user_page_size)
69         questions = objects_list.page(page)
70
71         return render_to_response('book.html', {
72             "book" : book,
73             "author_info" : author_info,
74             "author_rss" : author_rss,
75             "questions" : questions,
76             "context" : {
77                 'is_paginated' : True,
78                 'pages': objects_list.num_pages,
79                 'page': page,
80                 'has_previous': questions.has_previous(),
81                 'has_next': questions.has_next(),
82                 'previous': questions.previous_page_number(),
83                 'next': questions.next_page_number(),
84                 'base_url' : request.path + '?sort=%s&' % view_id,
85                 'pagesize' : user_page_size
86             }
87         }, context_instance=RequestContext(request))
88
89 @login_required
90 def ask_book(request, short_name):
91     if request.method == "POST":
92         form = AskForm(request.POST)
93         if form.is_valid():
94             added_at = datetime.datetime.now()
95             html = sanitize_html(markdowner.convert(form.cleaned_data['text']))
96             question = Question(
97                 title            = strip_tags(form.cleaned_data['title']),
98                 author           = request.user,
99                 added_at         = added_at,
100                 last_activity_at = added_at,
101                 last_activity_by = request.user,
102                 wiki             = form.cleaned_data['wiki'],
103                 tagnames         = form.cleaned_data['tags'].strip(),
104                 html             = html,
105                 summary          = strip_tags(html)[:120]
106             )
107             if question.wiki:
108                 question.last_edited_by = question.author
109                 question.last_edited_at = added_at
110                 question.wikified_at = added_at
111
112             question.save()
113
114             # create the first revision
115             QuestionRevision.objects.create(
116                 question   = question,
117                 revision   = 1,
118                 title      = question.title,
119                 author     = request.user,
120                 revised_at = added_at,
121                 tagnames   = question.tagnames,
122                 summary    = CONST['default_version'],
123                 text       = form.cleaned_data['text']
124             )
125
126             books = Book.objects.extra(where=['short_name = %s'], params=[short_name])
127             match_count = len(books)
128             if match_count == 1:
129                 # the book info
130                 book = books[0]
131                 book.questions.add(question)
132
133             return HttpResponseRedirect(question.get_absolute_url())
134     else:
135         form = AskForm()
136
137     tags = _get_tags_cache_json()
138     return render_to_response('ask.html', {
139         'form' : form,
140         'tags' : tags,
141         'email_validation_faq_url': reverse('faq') + '#validate',
142         }, context_instance=RequestContext(request))