Registered Tag as a value model.
[philo.git] / contrib / penfield / models.py
1 from django.conf import settings
2 from django.conf.urls.defaults import url, patterns, include
3 from django.db import models
4 from django.http import Http404
5 from django.template import loader, Context
6 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
7 from datetime import date, datetime
8 from philo.contrib.penfield.utils import FeedMultiViewMixin
9 from philo.contrib.penfield.validators import validate_pagination_count
10 from philo.exceptions import ViewCanNotProvideSubpath
11 from philo.models import Tag, Titled, Entity, MultiView, Page, register_value_model, TemplateField
12 from philo.utils import paginate
13
14
15 class Blog(Entity, Titled):
16         @property
17         def entry_tags(self):
18                 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
19                 return Tag.objects.filter(blogentries__blog=self).distinct()
20         
21         @property
22         def entry_dates(self):
23                 dates = {'year': self.entries.dates('date', 'year', order='DESC'), 'month': self.entries.dates('date', 'month', order='DESC'), 'day': self.entries.dates('date', 'day', order='DESC')}
24                 return dates
25
26
27 register_value_model(Blog)
28
29
30 class BlogEntry(Entity, Titled):
31         blog = models.ForeignKey(Blog, related_name='entries', blank=True, null=True)
32         author = models.ForeignKey(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='blogentries')
33         date = models.DateTimeField(default=None)
34         content = models.TextField()
35         excerpt = models.TextField(blank=True, null=True)
36         tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
37         
38         def save(self, *args, **kwargs):
39                 if self.date is None:
40                         self.date = datetime.now()
41                 super(BlogEntry, self).save(*args, **kwargs)
42         
43         class Meta:
44                 ordering = ['-date']
45                 verbose_name_plural = "blog entries"
46                 get_latest_by = "date"
47
48
49 register_value_model(BlogEntry)
50
51
52 class BlogView(MultiView, FeedMultiViewMixin):
53         ENTRY_PERMALINK_STYLE_CHOICES = (
54                 ('D', 'Year, month, and day'),
55                 ('M', 'Year and month'),
56                 ('Y', 'Year'),
57                 ('B', 'Custom base'),
58                 ('N', 'No base')
59         )
60         
61         blog = models.ForeignKey(Blog, related_name='blogviews')
62         
63         index_page = models.ForeignKey(Page, related_name='blog_index_related')
64         entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
65         entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
66         tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
67         tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
68         entries_per_page = models.IntegerField(blank=True, validators=[validate_pagination_count], null=True)
69         
70         entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
71         entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
72         tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
73         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
74         feeds_enabled = models.BooleanField()
75         list_var = 'entries'
76         
77         def __unicode__(self):
78                 return u'BlogView for %s' % self.blog.title
79         
80         @property
81         def per_page(self):
82                 return self.entries_per_page
83         
84         def get_reverse_params(self, obj):
85                 if isinstance(obj, BlogEntry):
86                         if obj.blog == self.blog:
87                                 kwargs = {'slug': obj.slug}
88                                 if self.entry_permalink_style in 'DMY':
89                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
90                                         if self.entry_permalink_style in 'DM':
91                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
92                                                 if self.entry_permalink_style == 'D':
93                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
94                                 return self.entry_view, [], kwargs
95                 elif isinstance(obj, Tag):
96                         if obj in self.get_tag_queryset():
97                                 return 'entries_by_tag', [], {'tag_slugs': obj.slug}
98                 elif isinstance(obj, (date, datetime)):
99                         kwargs = {
100                                 'year': str(obj.year).zfill(4),
101                                 'month': str(obj.month).zfill(2),
102                                 'day': str(obj.day).zfill(2)
103                         }
104                         return 'entries_by_day', [], kwargs
105                 raise ViewCanNotProvideSubpath
106         
107         @property
108         def urlpatterns(self):
109                 urlpatterns = patterns('',
110                         url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
111                 )
112                 if self.feeds_enabled:
113                         urlpatterns += patterns('',
114                                 url(r'^%s/(?P<tag_slugs>[-\w]+[-+/\w]*)/%s/' % (self.tag_permalink_base, self.feed_suffix), self.feed_view(self.get_entries_by_tag, 'entries_by_tag_feed'), name='entries_by_tag_feed'),
115                         )
116                 urlpatterns += patterns('',
117                         url(r'^%s/(?P<tag_slugs>[-\w]+[-+/\w]*)/' % self.tag_permalink_base, self.page_view(self.get_entries_by_tag, self.tag_page), name='entries_by_tag')
118                 )
119                 if self.tag_archive_page:
120                         urlpatterns += patterns('',
121                                 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view, 'tag_archive')
122                         )
123                 
124                 if self.entry_archive_page:
125                         if self.entry_permalink_style in 'DMY':
126                                 urlpatterns += patterns('',
127                                         url(r'^(?P<year>\d{4})/', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_year')))
128                                 )
129                                 if self.entry_permalink_style in 'DM':
130                                         urlpatterns += patterns('',
131                                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/?$', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_month'))),
132                                         )
133                                         if self.entry_permalink_style == 'D':
134                                                 urlpatterns += patterns('',
135                                                         url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_day')))
136                                                 )
137                 
138                 if self.entry_permalink_style == 'D':
139                         urlpatterns += patterns('',
140                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
141                         )
142                 elif self.entry_permalink_style == 'M':
143                         urlpatterns += patterns('',
144                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
145                         )
146                 elif self.entry_permalink_style == 'Y':
147                         urlpatterns += patterns('',
148                                 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
149                         )
150                 elif self.entry_permalink_style == 'B':
151                         urlpatterns += patterns('',
152                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
153                         )
154                 else:
155                         urlpatterns = patterns('',
156                                 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
157                         )
158                 return urlpatterns
159         
160         def get_context(self):
161                 return {'blog': self.blog}
162         
163         def get_entry_queryset(self):
164                 return self.blog.entries.all()
165         
166         def get_tag_queryset(self):
167                 return self.blog.entry_tags
168         
169         def get_all_entries(self, request, extra_context=None):
170                 return self.get_entry_queryset(), extra_context
171         
172         def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
173                 if not self.entry_archive_page:
174                         raise Http404
175                 entries = self.get_entry_queryset()
176                 if year:
177                         entries = entries.filter(date__year=year)
178                 if month:
179                         entries = entries.filter(date__month=month)
180                 if day:
181                         entries = entries.filter(date__day=day)
182                 
183                 context = extra_context or {}
184                 context.update({'year': year, 'month': month, 'day': day})
185                 return entries, context
186         
187         def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
188                 tag_slugs = tag_slugs.replace('+', '/').split('/')
189                 tags = self.get_tag_queryset().filter(slug__in=tag_slugs)
190                 
191                 if not tags:
192                         raise Http404
193                 
194                 # Raise a 404 on an incorrect slug.
195                 found_slugs = [tag.slug for tag in tags]
196                 for slug in tag_slugs:
197                         if slug and slug not in found_slugs:
198                                 raise Http404
199
200                 entries = self.get_entry_queryset()
201                 for tag in tags:
202                         entries = entries.filter(tags=tag)
203                 
204                 context = extra_context or {}
205                 context.update({'tags': tags})
206                 
207                 return entries, context
208         
209         def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
210                 entries = self.get_entry_queryset()
211                 if year:
212                         entries = entries.filter(date__year=year)
213                 if month:
214                         entries = entries.filter(date__month=month)
215                 if day:
216                         entries = entries.filter(date__day=day)
217                 try:
218                         entry = entries.get(slug=slug)
219                 except:
220                         raise Http404
221                 context = self.get_context()
222                 context.update(extra_context or {})
223                 context.update({'entry': entry})
224                 return self.entry_page.render_to_response(request, extra_context=context)
225         
226         def tag_archive_view(self, request, extra_context=None):
227                 if not self.tag_archive_page:
228                         raise Http404
229                 context = self.get_context()
230                 context.update(extra_context or {})
231                 context.update({
232                         'tags': self.get_tag_queryset()
233                 })
234                 return self.tag_archive_page.render_to_response(request, extra_context=context)
235         
236         def add_item(self, feed, obj, kwargs=None):
237                 title = loader.get_template("penfield/feeds/blog_entry/title.html")
238                 description = loader.get_template("penfield/feeds/blog_entry/description.html")
239                 defaults = {
240                         'title': title.render(Context({'entry': obj})),
241                         'description': description.render(Context({'entry': obj})),
242                         'author_name': obj.author.get_full_name(),
243                         'pubdate': obj.date
244                 }
245                 defaults.update(kwargs or {})
246                 super(BlogView, self).add_item(feed, obj, defaults)
247         
248         def get_feed(self, feed_type, extra_context, kwargs=None):
249                 tags = (extra_context or {}).get('tags', None)
250                 title = self.blog.title
251                 
252                 if tags is not None:
253                         title += " - %s" % ', '.join([tag.name for tag in tags])
254                 
255                 defaults = {
256                         'title': title
257                 }
258                 defaults.update(kwargs or {})
259                 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
260
261
262 class Newsletter(Entity, Titled):
263         pass
264
265
266 register_value_model(Newsletter)
267
268
269 class NewsletterArticle(Entity, Titled):
270         newsletter = models.ForeignKey(Newsletter, related_name='articles')
271         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
272         date = models.DateTimeField(default=None)
273         lede = TemplateField(null=True, blank=True, verbose_name='Summary')
274         full_text = TemplateField(db_index=True)
275         tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
276         
277         def save(self, *args, **kwargs):
278                 if self.date is None:
279                         self.date = datetime.now()
280                 super(NewsletterArticle, self).save(*args, **kwargs)
281         
282         class Meta:
283                 get_latest_by = 'date'
284                 ordering = ['-date']
285                 unique_together = (('newsletter', 'slug'),)
286
287
288 register_value_model(NewsletterArticle)
289
290
291 class NewsletterIssue(Entity, Titled):
292         newsletter = models.ForeignKey(Newsletter, related_name='issues')
293         numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
294         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
295         
296         class Meta:
297                 ordering = ['-numbering']
298                 unique_together = (('newsletter', 'numbering'),)
299
300
301 register_value_model(NewsletterIssue)
302
303
304 class NewsletterView(MultiView, FeedMultiViewMixin):
305         ARTICLE_PERMALINK_STYLE_CHOICES = (
306                 ('D', 'Year, month, and day'),
307                 ('M', 'Year and month'),
308                 ('Y', 'Year'),
309                 ('S', 'Slug only')
310         )
311         
312         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
313         
314         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
315         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
316         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
317         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
318         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
319         
320         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
321         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
322         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
323         
324         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
325         feeds_enabled = models.BooleanField()
326         list_var = 'articles'
327         
328         def __unicode__(self):
329                 return self.newsletter.__unicode__()
330         
331         def get_reverse_params(self, obj):
332                 if isinstance(obj, NewsletterArticle):
333                         if obj.newsletter == self.newsletter:
334                                 kwargs = {'slug': obj.slug}
335                                 if self.article_permalink_style in 'DMY':
336                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
337                                         if self.article_permalink_style in 'DM':
338                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
339                                                 if self.article_permalink_style == 'D':
340                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
341                                 return self.article_view, [], kwargs
342                 elif isinstance(obj, NewsletterIssue):
343                         if obj.newsletter == self.newsletter:
344                                 return 'issue', [], {'numbering': obj.numbering}
345                 elif isinstance(obj, (date, datetime)):
346                         kwargs = {
347                                 'year': str(obj.year).zfill(4),
348                                 'month': str(obj.month).zfill(2),
349                                 'day': str(obj.day).zfill(2)
350                         }
351                         return 'articles_by_day', [], kwargs
352                 raise ViewCanNotProvideSubpath
353         
354         @property
355         def urlpatterns(self):
356                 urlpatterns = patterns('',
357                         url(r'^', include(self.feed_patterns(self.get_all_articles, self.index_page, 'index'))),
358                         url(r'^(?:%s)/(?P<numbering>.+)/' % self.issue_permalink_base, include(self.feed_patterns(self.get_articles_by_issue, self.issue_page, 'issue')))
359                 )
360                 if self.issue_archive_page:
361                         urlpatterns += patterns('',
362                                 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view, 'issue_archive')
363                         )
364                 if self.article_archive_page:
365                         urlpatterns += patterns('',
366                                 url(r'^(?:%s)/' % self.article_permalink_base, include(self.feed_patterns(self.get_all_articles, self.article_archive_page, 'articles')))
367                         )
368                         if self.article_permalink_style in 'DMY':
369                                 urlpatterns += patterns('',
370                                         url(r'^(?:%s)/(?P<year>\d{4})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_year')))
371                                 )
372                                 if self.article_permalink_style in 'DM':
373                                         urlpatterns += patterns('',
374                                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_month')))
375                                         )
376                                         if self.article_permalink_style == 'D':
377                                                 urlpatterns += patterns('',
378                                                         url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/' % self.article_permalink_base, include(self.feed_patterns(self.get_articles_by_ymd, self.article_archive_page, 'articles_by_day')))
379                                                 )
380                 
381                 if self.article_permalink_style == 'Y':
382                         urlpatterns += patterns('',
383                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
384                         )
385                 elif self.article_permalink_style == 'M':
386                         urlpatterns += patterns('',
387                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
388                         )
389                 elif self.article_permalink_style == 'D':
390                         urlpatterns += patterns('',
391                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
392                         )
393                 else:   
394                         urlpatterns += patterns('',
395                                 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
396                         )
397                 
398                 return urlpatterns
399         
400         def get_context(self):
401                 return {'newsletter': self.newsletter}
402         
403         def get_article_queryset(self):
404                 return self.newsletter.articles.all()
405         
406         def get_issue_queryset(self):
407                 return self.newsletter.issues.all()
408         
409         def get_all_articles(self, request, extra_context=None):
410                 return self.get_article_queryset(), extra_context
411         
412         def get_articles_by_ymd(self, request, year, month=None, day=None, extra_context=None):
413                 articles = self.get_article_queryset().filter(date__year=year)
414                 if month:
415                         articles = articles.filter(date__month=month)
416                 if day:
417                         articles = articles.filter(date__day=day)
418                 return articles, extra_context
419         
420         def get_articles_by_issue(self, request, numbering, extra_context=None):
421                 try:
422                         issue = self.get_issue_queryset().get(numbering=numbering)
423                 except NewsletterIssue.DoesNotExist:
424                         raise Http404
425                 context = extra_context or {}
426                 context.update({'issue': issue})
427                 return self.get_article_queryset().filter(issues=issue), context
428         
429         def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
430                 articles = self.get_article_queryset()
431                 if year:
432                         articles = articles.filter(date__year=year)
433                 if month:
434                         articles = articles.filter(date__month=month)
435                 if day:
436                         articles = articles.filter(date__day=day)
437                 try:
438                         article = articles.get(slug=slug)
439                 except NewsletterArticle.DoesNotExist:
440                         raise Http404
441                 context = self.get_context()
442                 context.update(extra_context or {})
443                 context.update({'article': article})
444                 return self.article_page.render_to_response(request, extra_context=context)
445         
446         def issue_archive_view(self, request, extra_context):
447                 if not self.issue_archive_page:
448                         raise Http404
449                 context = self.get_context()
450                 context.update(extra_context or {})
451                 context.update({
452                         'issues': self.get_issue_queryset()
453                 })
454                 return self.issue_archive_page.render_to_response(request, extra_context=context)
455         
456         def add_item(self, feed, obj, kwargs=None):
457                 title = loader.get_template("penfield/feeds/newsletter_article/title.html")
458                 description = loader.get_template("penfield/feeds/newsletter_article/description.html")
459                 defaults = {
460                         'title': title.render(Context({'article': obj})),
461                         'author_name': ', '.join([author.get_full_name() for author in obj.authors.all()]),
462                         'pubdate': obj.date,
463                         'description': description.render(Context({'article': obj})),
464                         'categories': [tag.name for tag in obj.tags.all()]
465                 }
466                 defaults.update(kwargs or {})
467                 super(NewsletterView, self).add_item(feed, obj, defaults)
468         
469         def get_feed(self, feed_type, extra_context, kwargs=None):
470                 title = self.newsletter.title
471                 
472                 defaults = {
473                         'title': title
474                 }
475                 defaults.update(kwargs or {})
476                 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)