Minor bugfix: moved ConstantEmbedNode DoesNotExist reraising so that it actually...
[philo.git] / contrib / penfield / models.py
1 from django.db import models
2 from django.conf import settings
3 from philo.models import Tag, Titled, Entity, MultiView, Page, register_value_model, TemplateField
4 from philo.exceptions import ViewCanNotProvideSubpath
5 from django.conf.urls.defaults import url, patterns, include
6 from django.core.urlresolvers import reverse
7 from django.http import Http404
8 from datetime import datetime
9 from philo.utils import paginate
10 from philo.contrib.penfield.validators import validate_pagination_count
11 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
12 from philo.contrib.penfield.utils import FeedMultiViewMixin
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=datetime.now)
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         class Meta:
39                 ordering = ['-date']
40                 verbose_name_plural = "blog entries"
41
42
43 register_value_model(BlogEntry)
44
45
46 class BlogView(MultiView, FeedMultiViewMixin):
47         ENTRY_PERMALINK_STYLE_CHOICES = (
48                 ('D', 'Year, month, and day'),
49                 ('M', 'Year and month'),
50                 ('Y', 'Year'),
51                 ('B', 'Custom base'),
52                 ('N', 'No base')
53         )
54         
55         blog = models.ForeignKey(Blog, related_name='blogviews')
56         
57         index_page = models.ForeignKey(Page, related_name='blog_index_related')
58         entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
59         entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
60         tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
61         tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
62         entries_per_page = models.IntegerField(blank=True, validators=[validate_pagination_count], null=True)
63         
64         entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
65         entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
66         tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
67         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
68         feeds_enabled = models.BooleanField()
69         list_var = 'entries'
70         
71         def __unicode__(self):
72                 return u'BlogView for %s' % self.blog.title
73         
74         @property
75         def per_page(self):
76                 return self.entries_per_page
77         
78         def get_subpath(self, obj):
79                 if isinstance(obj, BlogEntry):
80                         if obj.blog == self.blog:
81                                 kwargs = {'slug': obj.slug}
82                                 if self.entry_permalink_style in 'DMY':
83                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
84                                         if self.entry_permalink_style in 'DM':
85                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
86                                                 if self.entry_permalink_style == 'D':
87                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
88                                 return reverse(self.entry_view, urlconf=self, kwargs=kwargs)
89                 elif isinstance(obj, Tag):
90                         if obj in self.blog.entry_tags:
91                                 return reverse('entries_by_tag', urlconf=self, kwargs={'tag_slugs': obj.slug})
92                 elif isinstance(obj, (str, unicode)):
93                         split_obj = obj.split(':')
94                         if len(split_obj) > 1:
95                                 kwargs = {}
96                                 try:
97                                         kwargs.update({'year': str(int(split_obj[1])).zfill(4)})
98                                         if len(split_obj) > 2:
99                                                 kwargs.update({'month': str(int(split_obj[2])).zfill(2)})
100                                                 if len(split_obj) > 3:
101                                                         kwargs.update({'day': str(int(split_obj[3])).zfill(2)})
102                                                         return reverse('entries_by_day', urlconf=self, kwargs=kwargs)
103                                                 return reverse('entries_by_month', urlconf=self, kwargs=kwargs)
104                                         return reverse('entries_by_year', urlconf=self, kwargs=kwargs)
105                                 except:
106                                         pass
107                 raise ViewCanNotProvideSubpath
108         
109         def get_context(self):
110                 return {'blog': self.blog}
111         
112         @property
113         def urlpatterns(self):
114                 urlpatterns = patterns('',
115                         url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
116                         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'),
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)
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_all_entries(self, request, node=None, extra_context=None):
161                 return self.blog.entries.all(), extra_context
162         
163         def get_entries_by_ymd(self, request, year=None, month=None, day=None, node=None, extra_context=None):
164                 if not self.entry_archive_page:
165                         raise Http404
166                 entries = self.blog.entries.all()
167                 if year:
168                         entries = entries.filter(date__year=year)
169                 if month:
170                         entries = entries.filter(date__month=month)
171                 if day:
172                         entries = entries.filter(date__day=day)
173                 
174                 context = extra_context or {}
175                 context.update({'year': year, 'month': month, 'day': day})
176                 return entries, context
177         
178         def get_entries_by_tag(self, request, tag_slugs, node=None, extra_context=None):
179                 tags = []
180                 for tag_slug in tag_slugs.replace('+', '/').split('/'):
181                         if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
182                                 try:
183                                         tag = self.blog.entry_tags.get(slug=tag_slug)
184                                 except:
185                                         raise Http404
186                                 tags.append(tag)
187                 if len(tags) <= 0:
188                         raise Http404
189
190                 entries = self.blog.entries.all()
191                 for tag in tags:
192                         entries = entries.filter(tags=tag)
193                 
194                 context = self.get_context()
195                 context.update(extra_context or {})
196                 context.update({'tags': tags})
197                 
198                 return entries, context
199         
200         def add_item(self, feed, obj, kwargs=None):
201                 defaults = {
202                         'title': obj.title,
203                         'description': obj.excerpt or obj.content,
204                         'author_name': obj.author.get_full_name(),
205                         'pubdate': obj.date
206                 }
207                 defaults.update(kwargs or {})
208                 super(BlogView, self).add_item(feed, obj, defaults)
209         
210         def get_feed(self, feed_type, extra_context, kwargs=None):
211                 tags = (extra_context or {}).get('tags', None)
212                 title = self.blog.title
213                 
214                 if tags is not None:
215                         title += " - %s" % ', '.join([tag.name for tag in tags])
216                 
217                 defaults = {
218                         'title': title
219                 }
220                 defaults.update(kwargs or {})
221                 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
222         
223         def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
224                 entries = self.blog.entries.all()
225                 if year:
226                         entries = entries.filter(date__year=year)
227                 if month:
228                         entries = entries.filter(date__month=month)
229                 if day:
230                         entries = entries.filter(date__day=day)
231                 try:
232                         entry = entries.get(slug=slug)
233                 except:
234                         raise Http404
235                 context = self.get_context()
236                 context.update(extra_context or {})
237                 context.update({'entry': entry})
238                 return self.entry_page.render_to_response(node, request, extra_context=context)
239         
240         def tag_archive_view(self, request, node=None, extra_context=None):
241                 if not self.tag_archive_page:
242                         raise Http404
243                 context = {}
244                 context.update(extra_context or {})
245                 context.update({'blog': self.blog})
246                 return self.tag_archive_page.render_to_response(node, request, extra_context=context)
247
248
249 class Newsletter(Entity, Titled):
250         pass
251
252
253 register_value_model(Newsletter)
254
255
256 class NewsletterArticle(Entity, Titled):
257         newsletter = models.ForeignKey(Newsletter, related_name='articles')
258         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
259         date = models.DateTimeField(default=datetime.now)
260         lede = TemplateField(null=True, blank=True, verbose_name='Summary')
261         full_text = TemplateField()
262         tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
263         
264         class Meta:
265                 get_latest_by = 'date'
266                 ordering = ['-date']
267                 unique_together = (('newsletter', 'slug'),)
268
269
270 register_value_model(NewsletterArticle)
271
272
273 class NewsletterIssue(Entity, Titled):
274         newsletter = models.ForeignKey(Newsletter, related_name='issues')
275         numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
276         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
277         
278         class Meta:
279                 ordering = ['-numbering']
280                 unique_together = (('newsletter', 'numbering'),)
281
282
283 register_value_model(NewsletterIssue)
284
285
286 class NewsletterView(MultiView, FeedMultiViewMixin):
287         ARTICLE_PERMALINK_STYLE_CHOICES = (
288                 ('D', 'Year, month, and day'),
289                 ('M', 'Year and month'),
290                 ('Y', 'Year'),
291                 ('S', 'Slug only')
292         )
293         
294         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
295         
296         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
297         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
298         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
299         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
300         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
301         
302         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
303         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
304         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
305         
306         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
307         feeds_enabled = models.BooleanField()
308         list_var = 'articles'
309         
310         def __unicode__(self):
311                 return self.newsletter.__unicode__()
312         
313         def get_subpath(self, obj):
314                 if isinstance(obj, NewsletterArticle):
315                         if obj.newsletter == self.newsletter:
316                                 kwargs = {'slug': obj.slug}
317                                 if self.article_permalink_style in 'DMY':
318                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
319                                         if self.article_permalink_style in 'DM':
320                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
321                                                 if self.article_permalink_style == 'D':
322                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
323                                 return reverse(self.article_view, urlconf=self, kwargs=kwargs)
324                 elif isinstance(obj, NewsletterIssue):
325                         if obj.newsletter == self.newsletter:
326                                 return reverse('issue', urlconf=self, kwargs={'numbering': obj.numbering})
327                 raise ViewCanNotProvideSubpath
328         
329         @property
330         def urlpatterns(self):
331                 urlpatterns = patterns('',
332                         url(r'^', include(self.feed_patterns(self.get_all_articles, self.index_page, 'index'))),
333                         url(r'^(?:%s)/(?P<numbering>.+)/' % self.issue_permalink_base, include(self.feed_patterns(self.get_articles_by_issue, self.issue_page, 'issue')))
334                 )
335                 if self.issue_archive_page:
336                         urlpatterns += patterns('',
337                                 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
338                         )
339                 if self.article_archive_page:
340                         urlpatterns += patterns('',
341                                 url(r'^(?:%s)/' % self.article_permalink_base, include(self.feed_patterns(self.get_all_articles, self.article_archive_page, 'articles')))
342                         )
343                         if self.article_permalink_style in 'DMY':
344                                 urlpatterns += patterns('',
345                                         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')))
346                                 )
347                                 if self.article_permalink_style in 'DM':
348                                         urlpatterns += patterns('',
349                                                 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')))
350                                         )
351                                         if self.article_permalink_style == 'D':
352                                                 urlpatterns += patterns('',
353                                                         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')))
354                                                 )
355                 
356                 if self.article_permalink_style == 'Y':
357                         urlpatterns += patterns('',
358                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
359                         )
360                 elif self.article_permalink_style == 'M':
361                         urlpatterns += patterns('',
362                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
363                         )
364                 elif self.article_permalink_style == 'D':
365                         urlpatterns += patterns('',
366                                 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)
367                         )
368                 else:   
369                         urlpatterns += patterns('',
370                                 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
371                         )
372                 
373                 return urlpatterns
374         
375         def get_context(self):
376                 return {'newsletter': self.newsletter}
377         
378         def get_all_articles(self, request, node, extra_context=None):
379                 return self.newsletter.articles.all(), extra_context
380         
381         def get_articles_by_ymd(self, request, year, month=None, day=None, node=None, extra_context=None):
382                 articles = self.newsletter.articles.filter(dat__year=year)
383                 if month:
384                         articles = articles.filter(date__month=month)
385                 if day:
386                         articles = articles.filter(date__day=day)
387                 return articles
388         
389         def get_articles_by_issue(self, request, numbering, node=None, extra_context=None):
390                 try:
391                         issue = self.newsletter.issues.get(numbering=numbering)
392                 except:
393                         raise Http404
394                 context = extra_context or {}
395                 context.update({'issue': issue})
396                 return issue.articles.all(), context
397         
398         def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
399                 articles = self.newsletter.articles.all()
400                 if year:
401                         articles = articles.filter(date__year=year)
402                 if month:
403                         articles = articles.filter(date__month=month)
404                 if day:
405                         articles = articles.filter(date__day=day)
406                 try:
407                         article = articles.get(slug=slug)
408                 except:
409                         raise Http404
410                 context = self.get_context()
411                 context.update(extra_context or {})
412                 context.update({'article': article})
413                 return self.article_page.render_to_response(node, request, extra_context=context)
414         
415         def issue_archive_view(self, request, node=None, extra_context=None):
416                 if not self.issue_archive_page:
417                         raise Http404
418                 context = {}
419                 context.update(extra_context or {})
420                 context.update({'newsletter': self.newsletter})
421                 return self.issue_archive_page.render_to_response(node, request, extra_context=context)
422         
423         def add_item(self, feed, obj, kwargs=None):
424                 defaults = {
425                         'title': obj.title,
426                         'author_name': ', '.join(obj.authors),
427                         'pubdate': obj.date,
428                         'description': obj.lede or obj.full_text,
429                         'categories': [tag.name for tag in obj.tags.all()]
430                 }
431                 defaults.update(kwargs or {})
432                 super(NewsletterView, self).add_item(feed, obj, defaults)
433         
434         def get_feed(self, feed_type, extra_context, kwargs=None):
435                 title = self.newsletter.title
436                 
437                 defaults = {
438                         'title': title
439                 }
440                 defaults.update(kwargs or {})
441                 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)