annotate gpp/forums/models.py @ 167:cf9f9d4c4d54

Adding a query to the forums to get all the topics with unread posts. This is for ticket #54.
author Brian Neal <bgneal@gmail.com>
date Sun, 24 Jan 2010 22:33:11 +0000
parents f7a6b8fe4556
children 6f14970b103a
rev   line source
bgneal@75 1 """
bgneal@75 2 Models for the forums application.
bgneal@75 3 """
bgneal@102 4 import datetime
bgneal@102 5
bgneal@75 6 from django.db import models
bgneal@100 7 from django.db.models import Q
bgneal@75 8 from django.contrib.auth.models import User, Group
bgneal@128 9
bgneal@128 10 from core.markup import site_markup
bgneal@75 11
bgneal@75 12
bgneal@75 13 class Category(models.Model):
bgneal@100 14 """
bgneal@100 15 Forums belong to a category, whose access may be assigned to groups.
bgneal@100 16 """
bgneal@75 17 name = models.CharField(max_length=80)
bgneal@75 18 slug = models.SlugField(max_length=80)
bgneal@75 19 position = models.IntegerField(blank=True, default=0)
bgneal@75 20 groups = models.ManyToManyField(Group, blank=True, null=True,
bgneal@75 21 help_text="If groups are assigned to this category, only members" \
bgneal@75 22 " of those groups can view this category.")
bgneal@75 23
bgneal@75 24 class Meta:
bgneal@75 25 ordering = ('position', )
bgneal@75 26 verbose_name_plural = 'Categories'
bgneal@75 27
bgneal@75 28 def __unicode__(self):
bgneal@75 29 return self.name
bgneal@75 30
bgneal@100 31 def can_access(self, user):
bgneal@100 32 """
bgneal@100 33 Checks to see if the given user has permission to access
bgneal@100 34 this category.
bgneal@100 35 If this category has no groups assigned to it, return true.
bgneal@100 36 Else, return true if the user belongs to a group that has been
bgneal@100 37 assigned to this category, and false otherwise.
bgneal@100 38 """
bgneal@100 39 if self.groups.count() == 0:
bgneal@100 40 return True
bgneal@100 41 if user.is_authenticated():
bgneal@100 42 return self.groups.filter(user__pk=user.id).count() > 0
bgneal@100 43 return False
bgneal@100 44
bgneal@100 45
bgneal@100 46 class ForumManager(models.Manager):
bgneal@100 47 """
bgneal@100 48 The manager for the Forum model. Provides a centralized place to
bgneal@100 49 put commonly used and useful queries.
bgneal@100 50 """
bgneal@100 51
bgneal@100 52 def forums_for_user(self, user):
bgneal@100 53 """
bgneal@100 54 Returns a queryset containing the forums that the given user can
bgneal@100 55 "see" due to authenticated status, superuser status and group membership.
bgneal@100 56 """
bgneal@167 57 qs = self._for_user(user)
bgneal@167 58 return qs.select_related('category', 'last_post', 'last_post__user')
bgneal@167 59
bgneal@167 60 def forum_ids_for_user(self, user):
bgneal@167 61 """Returns a list of forum IDs that the given user can "see"."""
bgneal@167 62 qs = self._for_user(user)
bgneal@167 63 return qs.values_list('id', flat=True)
bgneal@167 64
bgneal@167 65 def _for_user(self, user):
bgneal@167 66 """Common code for the xxx_for_user() methods."""
bgneal@100 67 if user.is_superuser:
bgneal@100 68 qs = self.all()
bgneal@100 69 else:
bgneal@167 70 user_groups = user.groups.all() if user.is_authenticated() else []
bgneal@167 71 qs = self.filter(Q(category__groups__isnull=True) |
bgneal@100 72 Q(category__groups__in=user_groups))
bgneal@167 73 return qs
bgneal@100 74
bgneal@75 75
bgneal@75 76 class Forum(models.Model):
bgneal@100 77 """
bgneal@100 78 A forum is a collection of topics.
bgneal@100 79 """
bgneal@75 80 category = models.ForeignKey(Category, related_name='forums')
bgneal@75 81 name = models.CharField(max_length=80)
bgneal@75 82 slug = models.SlugField(max_length=80)
bgneal@75 83 description = models.TextField(blank=True, default='')
bgneal@75 84 position = models.IntegerField(blank=True, default=0)
bgneal@75 85 moderators = models.ManyToManyField(Group, blank=True, null=True)
bgneal@75 86
bgneal@75 87 # denormalized fields to reduce database hits
bgneal@75 88 topic_count = models.IntegerField(blank=True, default=0)
bgneal@75 89 post_count = models.IntegerField(blank=True, default=0)
bgneal@75 90 last_post = models.OneToOneField('Post', blank=True, null=True,
bgneal@75 91 related_name='parent_forum')
bgneal@75 92
bgneal@100 93 objects = ForumManager()
bgneal@100 94
bgneal@75 95 class Meta:
bgneal@75 96 ordering = ('position', )
bgneal@75 97
bgneal@75 98 def __unicode__(self):
bgneal@75 99 return self.name
bgneal@75 100
bgneal@81 101 @models.permalink
bgneal@81 102 def get_absolute_url(self):
bgneal@81 103 return ('forums-forum_index', [self.slug])
bgneal@81 104
bgneal@75 105 def topic_count_update(self):
bgneal@75 106 """Call to notify the forum that its topic count has been updated."""
bgneal@75 107 self.topic_count = Topic.objects.filter(forum=self).count()
bgneal@75 108
bgneal@75 109 def post_count_update(self):
bgneal@75 110 """Call to notify the forum that its post count has been updated."""
bgneal@75 111 my_posts = Post.objects.filter(topic__forum=self)
bgneal@75 112 self.post_count = my_posts.count()
bgneal@75 113 if self.post_count > 0:
bgneal@75 114 self.last_post = my_posts[self.post_count - 1]
bgneal@75 115 else:
bgneal@75 116 self.last_post = None
bgneal@75 117
bgneal@112 118 def sync(self):
bgneal@112 119 """
bgneal@112 120 Call to notify the forum that it needs to recompute its
bgneal@112 121 denormalized fields.
bgneal@112 122 """
bgneal@112 123 self.topic_count_update()
bgneal@112 124 self.post_count_update()
bgneal@112 125
bgneal@107 126 def last_post_pre_delete(self):
bgneal@107 127 """
bgneal@107 128 Call this function prior to deleting the last post in the forum.
bgneal@107 129 A new last post will be found, if one exists.
bgneal@107 130 This is to avoid the Django cascading delete issue.
bgneal@107 131 """
bgneal@107 132 try:
bgneal@107 133 self.last_post = \
bgneal@107 134 Post.objects.filter(topic__forum=self).exclude(pk=self.last_post.pk).latest()
bgneal@107 135 except Post.DoesNotExist:
bgneal@107 136 self.last_post = None
bgneal@107 137
bgneal@113 138 def catchup(self, user, flv=None):
bgneal@113 139 """
bgneal@113 140 Call to mark this forum all caught up for the given user (i.e. mark all topics
bgneal@113 141 read for this user).
bgneal@113 142 """
bgneal@113 143 TopicLastVisit.objects.filter(user=user, topic__forum=self).delete()
bgneal@113 144 if flv is None:
bgneal@113 145 try:
bgneal@113 146 flv = ForumLastVisit.objects.get(user=user, forum=self)
bgneal@113 147 except ForumLastVisit.DoesNotExist:
bgneal@113 148 flv = ForumLastVisit(user=user, forum=self)
bgneal@113 149
bgneal@113 150 now = datetime.datetime.now()
bgneal@113 151 flv.begin_date = now
bgneal@113 152 flv.end_date = now
bgneal@113 153 flv.save()
bgneal@113 154
bgneal@75 155
bgneal@75 156 class Topic(models.Model):
bgneal@100 157 """
bgneal@100 158 A topic is a thread of discussion, consisting of a series of posts.
bgneal@100 159 """
bgneal@75 160 forum = models.ForeignKey(Forum, related_name='topics')
bgneal@75 161 name = models.CharField(max_length=255)
bgneal@75 162 creation_date = models.DateTimeField(auto_now_add=True)
bgneal@75 163 user = models.ForeignKey(User)
bgneal@75 164 view_count = models.IntegerField(blank=True, default=0)
bgneal@75 165 sticky = models.BooleanField(blank=True, default=False)
bgneal@75 166 locked = models.BooleanField(blank=True, default=False)
bgneal@75 167
bgneal@75 168 # denormalized fields to reduce database hits
bgneal@75 169 post_count = models.IntegerField(blank=True, default=0)
bgneal@102 170 update_date = models.DateTimeField()
bgneal@75 171 last_post = models.OneToOneField('Post', blank=True, null=True,
bgneal@75 172 related_name='parent_topic')
bgneal@75 173
bgneal@75 174 class Meta:
bgneal@75 175 ordering = ('-sticky', '-update_date', )
bgneal@75 176
bgneal@75 177 def __unicode__(self):
bgneal@75 178 return self.name
bgneal@75 179
bgneal@82 180 @models.permalink
bgneal@82 181 def get_absolute_url(self):
bgneal@82 182 return ('forums-topic_index', [self.pk])
bgneal@82 183
bgneal@75 184 def post_count_update(self):
bgneal@75 185 """
bgneal@75 186 Call this function to notify the topic instance that its post count
bgneal@75 187 has changed.
bgneal@75 188 """
bgneal@75 189 my_posts = Post.objects.filter(topic=self)
bgneal@75 190 self.post_count = my_posts.count()
bgneal@75 191 if self.post_count > 0:
bgneal@75 192 self.last_post = my_posts[self.post_count - 1]
bgneal@75 193 self.update_date = self.last_post.creation_date
bgneal@75 194 else:
bgneal@75 195 self.last_post = None
bgneal@75 196 self.update_date = self.creation_date
bgneal@75 197
bgneal@83 198 def reply_count(self):
bgneal@83 199 """
bgneal@83 200 Returns the number of replies to a topic. The first post
bgneal@83 201 doesn't count as a reply.
bgneal@83 202 """
bgneal@83 203 if self.post_count > 1:
bgneal@83 204 return self.post_count - 1
bgneal@83 205 return 0
bgneal@83 206
bgneal@102 207 def save(self, *args, **kwargs):
bgneal@102 208 if not self.id:
bgneal@102 209 now = datetime.datetime.now()
bgneal@102 210 self.creation_date = now
bgneal@102 211 self.update_date = now
bgneal@102 212
bgneal@102 213 super(Topic, self).save(*args, **kwargs)
bgneal@102 214
bgneal@107 215 def last_post_pre_delete(self):
bgneal@107 216 """
bgneal@107 217 Call this function prior to deleting the last post in the topic.
bgneal@107 218 A new last post will be found, if one exists.
bgneal@107 219 This is to avoid the Django cascading delete issue.
bgneal@107 220 """
bgneal@107 221 try:
bgneal@107 222 self.last_post = \
bgneal@107 223 Post.objects.filter(topic=self).exclude(pk=self.last_post.pk).latest()
bgneal@107 224 except Post.DoesNotExist:
bgneal@107 225 self.last_post = None
bgneal@107 226
bgneal@75 227
bgneal@75 228 class Post(models.Model):
bgneal@100 229 """
bgneal@100 230 A post is an instance of a user's single contribution to a topic.
bgneal@100 231 """
bgneal@75 232 topic = models.ForeignKey(Topic, related_name='posts')
bgneal@75 233 user = models.ForeignKey(User, related_name='posts')
bgneal@75 234 creation_date = models.DateTimeField(auto_now_add=True)
bgneal@115 235 update_date = models.DateTimeField(null=True)
bgneal@75 236 body = models.TextField()
bgneal@75 237 html = models.TextField()
bgneal@83 238 user_ip = models.IPAddressField(blank=True, default='', null=True)
bgneal@75 239
bgneal@75 240 class Meta:
bgneal@97 241 ordering = ('creation_date', )
bgneal@107 242 get_latest_by = 'creation_date'
bgneal@75 243
bgneal@91 244 @models.permalink
bgneal@91 245 def get_absolute_url(self):
bgneal@91 246 return ('forums-goto_post', [self.pk])
bgneal@91 247
bgneal@75 248 def summary(self):
bgneal@75 249 LIMIT = 50
bgneal@75 250 if len(self.body) < LIMIT:
bgneal@75 251 return self.body
bgneal@75 252 return self.body[:LIMIT] + '...'
bgneal@75 253
bgneal@75 254 def __unicode__(self):
bgneal@75 255 return self.summary()
bgneal@75 256
bgneal@75 257 def save(self, *args, **kwargs):
bgneal@128 258 self.html = site_markup(self.body)
bgneal@75 259 super(Post, self).save(*args, **kwargs)
bgneal@75 260
bgneal@75 261 def delete(self, *args, **kwargs):
bgneal@75 262 first_post_id = self.topic.posts.all()[0].id
bgneal@75 263 super(Post, self).delete(*args, **kwargs)
bgneal@75 264 if self.id == first_post_id:
bgneal@75 265 self.topic.delete()
bgneal@75 266
bgneal@113 267 def has_been_edited(self):
bgneal@115 268 return self.update_date is not None
bgneal@115 269
bgneal@115 270 def touch(self):
bgneal@115 271 """Call this function to indicate the post has been edited."""
bgneal@115 272 self.update_date = datetime.datetime.now()
bgneal@113 273
bgneal@98 274
bgneal@98 275 class FlaggedPost(models.Model):
bgneal@98 276 """This model represents a user flagging a post as inappropriate."""
bgneal@98 277 user = models.ForeignKey(User)
bgneal@98 278 post = models.ForeignKey(Post)
bgneal@98 279 flag_date = models.DateTimeField(auto_now_add=True)
bgneal@98 280
bgneal@98 281 def __unicode__(self):
bgneal@98 282 return u'Post ID %s flagged by %s' % (self.post.id, self.user.username)
bgneal@98 283
bgneal@98 284 class Meta:
bgneal@98 285 ordering = ('flag_date', )
bgneal@98 286
bgneal@98 287 def get_post_url(self):
bgneal@98 288 return '<a href="%s">Post</a>' % self.post.get_absolute_url()
bgneal@98 289 get_post_url.allow_tags = True
bgneal@98 290
bgneal@113 291
bgneal@113 292 class ForumLastVisit(models.Model):
bgneal@113 293 """
bgneal@113 294 This model records the last time a user visited a forum.
bgneal@113 295 It is used to compute if a user has unread topics in a forum.
bgneal@113 296 We keep track of a window of time, delimited by begin_date and end_date.
bgneal@113 297 Topics updated within this window are tracked, and may have TopicLastVisit
bgneal@113 298 objects.
bgneal@113 299 Marking a forum as all read sets the begin_date equal to the end_date.
bgneal@113 300 """
bgneal@113 301 user = models.ForeignKey(User)
bgneal@113 302 forum = models.ForeignKey(Forum)
bgneal@113 303 begin_date = models.DateTimeField()
bgneal@113 304 end_date = models.DateTimeField()
bgneal@113 305
bgneal@113 306 class Meta:
bgneal@113 307 unique_together = ('user', 'forum')
bgneal@113 308 ordering = ('-end_date', )
bgneal@113 309
bgneal@113 310 def __unicode__(self):
bgneal@113 311 return u'Forum: %d User: %d Date: %s' % (self.forum.id, self.user.id,
bgneal@113 312 self.end_date.strftime('%Y-%m-%d %H:%M:%S'))
bgneal@113 313
bgneal@113 314 def is_caught_up(self):
bgneal@113 315 return self.begin_date == self.end_date
bgneal@113 316
bgneal@113 317
bgneal@113 318 class TopicLastVisit(models.Model):
bgneal@113 319 """
bgneal@113 320 This model records the last time a user read a topic.
bgneal@113 321 Objects of this class exist for the window specified in the
bgneal@113 322 corresponding ForumLastVisit object.
bgneal@113 323 """
bgneal@113 324 user = models.ForeignKey(User)
bgneal@113 325 topic = models.ForeignKey(Topic)
bgneal@113 326 last_visit = models.DateTimeField()
bgneal@113 327
bgneal@113 328 class Meta:
bgneal@113 329 unique_together = ('user', 'topic')
bgneal@113 330 ordering = ('-last_visit', )
bgneal@113 331
bgneal@113 332 def __unicode__(self):
bgneal@113 333 return u'Topic: %d User: %d Date: %s' % (self.topic.id, self.user.id,
bgneal@113 334 self.last_visit.strftime('%Y-%m-%d %H:%M:%S'))
bgneal@113 335
bgneal@113 336 def save(self, *args, **kwargs):
bgneal@116 337 if self.id is None:
bgneal@113 338 self.touch()
bgneal@113 339 super(TopicLastVisit, self).save(*args, **kwargs)
bgneal@113 340
bgneal@113 341 def touch(self):
bgneal@113 342 self.last_visit = datetime.datetime.now()
bgneal@164 343
bgneal@164 344
bgneal@164 345 class Statistic(models.Model):
bgneal@164 346 """
bgneal@164 347 This model keeps track of forum statistics. Currently, the only statistic
bgneal@164 348 is the maximum number of users online. This stat is computed by a mgmt.
bgneal@164 349 command that is run on a cron job to peek at the "users_online" dict
bgneal@164 350 that is maintained in cache by the forums middleware.
bgneal@164 351 """
bgneal@164 352 max_users = models.IntegerField()
bgneal@164 353 max_users_date = models.DateTimeField()
bgneal@164 354
bgneal@164 355 def __unicode__(self):
bgneal@164 356 return u'%d users on %s' % (self.max_users,
bgneal@164 357 self.max_users_date.strftime('%Y-%m-%d %H:%M:%S'))
bgneal@164 358
bgneal@164 359 def save(self, *args, **kwargs):
bgneal@164 360 self.max_users_date = datetime.datetime.now()
bgneal@164 361 super(Statistic, self).save(*args, **kwargs)