Posting!
[zzz-spline-forum.git] / splinext / forum / controllers / forum.py
1 import logging
2
3 from pylons import config, request, response, session, tmpl_context as c, url
4 from pylons.controllers.util import abort, redirect_to
5 from routes import request_config
6 from sqlalchemy.orm.exc import NoResultFound
7 import wtforms
8 from wtforms import fields
9
10 from spline.model import meta
11 from spline.lib import helpers as h
12 from spline.lib.base import BaseController, render
13 from splinext.forum import model as forum_model
14
15 log = logging.getLogger(__name__)
16
17
18 class WritePostForm(wtforms.Form):
19 content = fields.TextAreaField('Content')
20
21 class ForumController(BaseController):
22
23 def forums(self):
24 c.forums = meta.Session.query(forum_model.Forum) \
25 .order_by(forum_model.Forum.id.asc())
26 return render('/forum/forums.mako')
27
28 def threads(self, forum_id):
29 try:
30 c.forum = meta.Session.query(forum_model.Forum).get(forum_id)
31 except NoResultFound:
32 abort(404)
33
34 c.threads = c.forum.threads
35
36 return render('/forum/threads.mako')
37
38 def posts(self, forum_id, thread_id):
39 try:
40 c.thread = meta.Session.query(forum_model.Thread) \
41 .filter_by(id=thread_id, forum_id=forum_id).one()
42 except NoResultFound:
43 abort(404)
44
45 return render('/forum/posts.mako')
46
47
48 def write(self, forum_id, thread_id):
49 """Provides a form for posting to a thread."""
50 if not c.user.can('create_forum_post'):
51 abort(403)
52
53 try:
54 c.thread = meta.Session.query(forum_model.Thread) \
55 .filter_by(id=thread_id, forum_id=forum_id).one()
56 except NoResultFound:
57 abort(404)
58
59 c.form = WritePostForm(request.params)
60 c.write_mode = 'post'
61
62 if request.method != 'POST' or not c.form.validate():
63 # Failure or initial request; show the form
64 return render('/forum/write.mako')
65
66
67 # Otherwise, add the post.
68 c.thread = meta.Session.query(forum_model.Thread) \
69 .with_lockmode('update') \
70 .get(c.thread.id)
71
72 post = forum_model.Post(
73 position = c.thread.post_count + 1,
74 author_user_id = c.user.id,
75 content = c.form.content.data,
76 )
77
78 c.thread.posts.append(post)
79 c.thread.post_count += 1
80
81 meta.Session.commit()
82
83 # Redirect to the thread
84 # XXX probably to the post instead; anchor? depends on paging scheme
85 h.flash('Your uniqueness has been added to our own.')
86 redirect_to(controller='forum', action='posts',
87 forum_id=forum_id, thread_id=thread_id,
88 _code=303)