Created
April 19, 2010 09:10
-
-
Save csytan/370861 to your computer and use it in GitHub Desktop.
Threaded Comments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Topic(BaseModel): | |
author = db.ReferenceProperty(User, required=True, collection_name='topics') | |
title = db.StringProperty() | |
body = db.TextProperty() | |
@classmethod | |
def topics(cls): | |
topics = cls.all().order('-updated').fetch(100) | |
prefetch_refprop(topics, cls.author) | |
return topics | |
def replies(self): | |
"""Fetches the topic's comments & sets each comment's 'replies' attribute""" | |
keys = {} | |
comments = self.comment_set.order('-created').fetch(1000) | |
for comment in comments: | |
keys[str(comment.key())] = comment | |
comment.replies = [] | |
for comment in comments: | |
parent_key = Comment.reply_to.get_value_for_datastore(comment) | |
parent = keys.get(str(parent_key)) | |
if parent: | |
parent.replies.append(comment) | |
replies = [c for c in comments if not c.reply_to] | |
prefetch_refprop(replies, Comment.author) | |
return replies | |
class Comment(BaseModel): | |
author = db.ReferenceProperty(User, required=True, collection_name='comments') | |
topic = db.ReferenceProperty(required=True) | |
reply_to = db.SelfReferenceProperty(collection_name='reply_to_set') | |
body = db.TextProperty() | |
### views.py ### | |
class Video(BaseHandler): | |
def get(self, id): | |
... | |
def render_comments(self, comments): | |
return self.render_string('_comment.html', comments=comments) | |
### _comment.html ### | |
{% for comment in comments %} | |
<div class="comment"> | |
<p class="info"> | |
by {{ comment.author }} | |
{{ relative_date(comment.created) }} | |
</p> | |
{{ escape(comment.text) }} | |
<a data-id="{{ comment.id }}" class="reply">reply</a> | |
{{ handler.render_comments(comment.replies) }} | |
</div> | |
{% end %} | |
### thread.html ### | |
<form id="reply_box" action="" method="post"> | |
{{ xsrf_form_html() }} | |
<input type="hidden" name="action" value="comment"> | |
<label for="author">Author</label> | |
<input id="author" type="text" name="author" tabindex="1"> | |
<label for="text">Text</label> | |
<textarea id="text" name="text" tabindex="2"></textarea> | |
<input type="submit" value="Post" tabindex="3"> | |
</form> | |
{{ handler.render_comments(replies) }} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment