Minor correction to embed template tag: updating the context adds an additional conte...
[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.http import Http404
7 from datetime import date, datetime
8 from philo.utils import paginate
9 from philo.contrib.penfield.validators import validate_pagination_count
10 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
11 from philo.contrib.penfield.utils import FeedMultiViewMixin
12
13
14 class Blog(Entity, Titled):
15         @property
16         def entry_tags(self):
17                 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
18                 return Tag.objects.filter(blogentries__blog=self).distinct()
19         
20         @property
21         def entry_dates(self):
22                 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')}
23                 return dates
24
25
26 register_value_model(Blog)
27
28
29 class BlogEntry(Entity, Titled):
30         blog = models.ForeignKey(Blog, related_name='entries', blank=True, null=True)
31         author = models.ForeignKey(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='blogentries')
32         date = models.DateTimeField(default=datetime.now)
33         content = models.TextField()
34         excerpt = models.TextField(blank=True, null=True)
35         tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
36         
37         class Meta:
38                 ordering = ['-date']
39                 verbose_name_plural = "blog entries"
40                 get_latest_by = "date"
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_reverse_params(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 self.entry_view, [], kwargs
89                 elif isinstance(obj, Tag):
90                         if obj in self.blog.entry_tags:
91                                 return 'entries_by_tag', [], {'tag_slugs': obj.slug}
92                 elif isinstance(obj, (date, datetime)):
93                         kwargs = {
94                                 'year': str(obj.year).zfill(4),
95                                 'month': str(obj.month).zfill(2),
96                                 'day': str(obj.day).zfill(2)
97                         }
98                         return 'entries_by_day', [], kwargs
99                 raise ViewCanNotProvideSubpath
100         
101         def get_context(self):
102                 return {'blog': self.blog}
103         
104         @property
105         def urlpatterns(self):
106                 urlpatterns = patterns('',
107                         url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
108                 )
109                 if self.feeds_enabled:
110                         urlpatterns += patterns('',
111                                 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'),
112                         )
113                 urlpatterns += patterns('',
114                         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')
115                 )
116                 if self.tag_archive_page:
117                         urlpatterns += patterns('',
118                                 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view)
119                         )
120                 
121                 if self.entry_archive_page:
122                         if self.entry_permalink_style in 'DMY':
123                                 urlpatterns += patterns('',
124                                         url(r'^(?P<year>\d{4})/', include(self.feed_patterns(self.get_entries_by_ymd, self.entry_archive_page, 'entries_by_year')))
125                                 )
126                                 if self.entry_permalink_style in 'DM':
127                                         urlpatterns += patterns('',
128                                                 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'))),
129                                         )
130                                         if self.entry_permalink_style == 'D':
131                                                 urlpatterns += patterns('',
132                                                         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')))
133                                                 )
134                 
135                 if self.entry_permalink_style == 'D':
136                         urlpatterns += patterns('',
137                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
138                         )
139                 elif self.entry_permalink_style == 'M':
140                         urlpatterns += patterns('',
141                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
142                         )
143                 elif self.entry_permalink_style == 'Y':
144                         urlpatterns += patterns('',
145                                 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
146                         )
147                 elif self.entry_permalink_style == 'B':
148                         urlpatterns += patterns('',
149                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
150                         )
151                 else:
152                         urlpatterns = patterns('',
153                                 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
154                         )
155                 return urlpatterns
156         
157         def get_all_entries(self, request, extra_context=None):
158                 return self.blog.entries.all(), extra_context
159         
160         def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
161                 if not self.entry_archive_page:
162                         raise Http404
163                 entries = self.blog.entries.all()
164                 if year:
165                         entries = entries.filter(date__year=year)
166                 if month:
167                         entries = entries.filter(date__month=month)
168                 if day:
169                         entries = entries.filter(date__day=day)
170                 
171                 context = extra_context or {}
172                 context.update({'year': year, 'month': month, 'day': day})
173                 return entries, context
174         
175         def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
176                 tags = []
177                 for tag_slug in tag_slugs.replace('+', '/').split('/'):
178                         if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
179                                 try:
180                                         tag = self.blog.entry_tags.get(slug=tag_slug)
181                                 except:
182                                         raise Http404
183                                 tags.append(tag)
184                 if len(tags) <= 0:
185                         raise Http404
186
187                 entries = self.blog.entries.all()
188                 for tag in tags:
189                         entries = entries.filter(tags=tag)
190                 
191                 context = self.get_context()
192                 context.update(extra_context or {})
193                 context.update({'tags': tags})
194                 
195                 return entries, context
196         
197         def add_item(self, feed, obj, kwargs=None):
198                 defaults = {
199                         'title': obj.title,
200                         'description': obj.excerpt or obj.content,
201                         'author_name': obj.author.get_full_name(),
202                         'pubdate': obj.date
203                 }
204                 defaults.update(kwargs or {})
205                 super(BlogView, self).add_item(feed, obj, defaults)
206         
207         def get_feed(self, feed_type, extra_context, kwargs=None):
208                 tags = (extra_context or {}).get('tags', None)
209                 title = self.blog.title
210                 
211                 if tags is not None:
212                         title += " - %s" % ', '.join([tag.name for tag in tags])
213                 
214                 defaults = {
215                         'title': title
216                 }
217                 defaults.update(kwargs or {})
218                 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
219         
220         def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
221                 entries = self.blog.entries.all()
222                 if year:
223                         entries = entries.filter(date__year=year)
224                 if month:
225                         entries = entries.filter(date__month=month)
226                 if day:
227                         entries = entries.filter(date__day=day)
228                 try:
229                         entry = entries.get(slug=slug)
230                 except:
231                         raise Http404
232                 context = self.get_context()
233                 context.update(extra_context or {})
234                 context.update({'entry': entry})
235                 return self.entry_page.render_to_response(request, extra_context=context)
236         
237         def tag_archive_view(self, request, extra_context=None):
238                 if not self.tag_archive_page:
239                         raise Http404
240                 context = {}
241                 context.update(extra_context or {})
242                 context.update({'blog': self.blog})
243                 return self.tag_archive_page.render_to_response(request, extra_context=context)
244
245
246 class Newsletter(Entity, Titled):
247         pass
248
249
250 register_value_model(Newsletter)
251
252
253 class NewsletterArticle(Entity, Titled):
254         newsletter = models.ForeignKey(Newsletter, related_name='articles')
255         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
256         date = models.DateTimeField(default=datetime.now)
257         lede = TemplateField(null=True, blank=True, verbose_name='Summary')
258         full_text = TemplateField(db_index=True)
259         tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
260         
261         class Meta:
262                 get_latest_by = 'date'
263                 ordering = ['-date']
264                 unique_together = (('newsletter', 'slug'),)
265
266
267 register_value_model(NewsletterArticle)
268
269
270 class NewsletterIssue(Entity, Titled):
271         newsletter = models.ForeignKey(Newsletter, related_name='issues')
272         numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
273         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
274         
275         class Meta:
276                 ordering = ['-numbering']
277                 unique_together = (('newsletter', 'numbering'),)
278
279
280 register_value_model(NewsletterIssue)
281
282
283 class NewsletterView(MultiView, FeedMultiViewMixin):
284         ARTICLE_PERMALINK_STYLE_CHOICES = (
285                 ('D', 'Year, month, and day'),
286                 ('M', 'Year and month'),
287                 ('Y', 'Year'),
288                 ('S', 'Slug only')
289         )
290         
291         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
292         
293         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
294         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
295         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
296         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
297         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
298         
299         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
300         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
301         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
302         
303         feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
304         feeds_enabled = models.BooleanField()
305         list_var = 'articles'
306         
307         def __unicode__(self):
308                 return self.newsletter.__unicode__()
309         
310         def get_reverse_params(self, obj):
311                 if isinstance(obj, NewsletterArticle):
312                         if obj.newsletter == self.newsletter:
313                                 kwargs = {'slug': obj.slug}
314                                 if self.article_permalink_style in 'DMY':
315                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
316                                         if self.article_permalink_style in 'DM':
317                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
318                                                 if self.article_permalink_style == 'D':
319                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
320                                 return self.article_view, [], kwargs
321                 elif isinstance(obj, NewsletterIssue):
322                         if obj.newsletter == self.newsletter:
323                                 return 'issue', [], {'numbering': obj.numbering}
324                 elif isinstance(obj, (date, datetime)):
325                         kwargs = {
326                                 'year': str(obj.year).zfill(4),
327                                 'month': str(obj.month).zfill(2),
328                                 'day': str(obj.day).zfill(2)
329                         }
330                         return 'articles_by_day', [], kwargs
331                 raise ViewCanNotProvideSubpath
332         
333         @property
334         def urlpatterns(self):
335                 urlpatterns = patterns('',
336                         url(r'^', include(self.feed_patterns(self.get_all_articles, self.index_page, 'index'))),
337                         url(r'^(?:%s)/(?P<numbering>.+)/' % self.issue_permalink_base, include(self.feed_patterns(self.get_articles_by_issue, self.issue_page, 'issue')))
338                 )
339                 if self.issue_archive_page:
340                         urlpatterns += patterns('',
341                                 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
342                         )
343                 if self.article_archive_page:
344                         urlpatterns += patterns('',
345                                 url(r'^(?:%s)/' % self.article_permalink_base, include(self.feed_patterns(self.get_all_articles, self.article_archive_page, 'articles')))
346                         )
347                         if self.article_permalink_style in 'DMY':
348                                 urlpatterns += patterns('',
349                                         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')))
350                                 )
351                                 if self.article_permalink_style in 'DM':
352                                         urlpatterns += patterns('',
353                                                 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')))
354                                         )
355                                         if self.article_permalink_style == 'D':
356                                                 urlpatterns += patterns('',
357                                                         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')))
358                                                 )
359                 
360                 if self.article_permalink_style == 'Y':
361                         urlpatterns += patterns('',
362                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
363                         )
364                 elif self.article_permalink_style == 'M':
365                         urlpatterns += patterns('',
366                                 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
367                         )
368                 elif self.article_permalink_style == 'D':
369                         urlpatterns += patterns('',
370                                 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)
371                         )
372                 else:   
373                         urlpatterns += patterns('',
374                                 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
375                         )
376                 
377                 return urlpatterns
378         
379         def get_context(self):
380                 return {'newsletter': self.newsletter}
381         
382         def get_all_articles(self, request, extra_context=None):
383                 return self.newsletter.articles.all(), extra_context
384         
385         def get_articles_by_ymd(self, request, year, month=None, day=None, extra_context=None):
386                 articles = self.newsletter.articles.filter(dat__year=year)
387                 if month:
388                         articles = articles.filter(date__month=month)
389                 if day:
390                         articles = articles.filter(date__day=day)
391                 return articles
392         
393         def get_articles_by_issue(self, request, numbering, extra_context=None):
394                 try:
395                         issue = self.newsletter.issues.get(numbering=numbering)
396                 except NewsletterIssue.DoesNotExist:
397                         raise Http404
398                 context = extra_context or {}
399                 context.update({'issue': issue})
400                 return issue.articles.all(), context
401         
402         def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
403                 articles = self.newsletter.articles.all()
404                 if year:
405                         articles = articles.filter(date__year=year)
406                 if month:
407                         articles = articles.filter(date__month=month)
408                 if day:
409                         articles = articles.filter(date__day=day)
410                 try:
411                         article = articles.get(slug=slug)
412                 except NewsletterArticle.DoesNotExist:
413                         raise Http404
414                 context = self.get_context()
415                 context.update(extra_context or {})
416                 context.update({'article': article})
417                 return self.article_page.render_to_response(request, extra_context=context)
418         
419         def issue_archive_view(self, request, extra_context=None):
420                 if not self.issue_archive_page:
421                         raise Http404
422                 context = {}
423                 context.update(extra_context or {})
424                 context.update({'newsletter': self.newsletter})
425                 return self.issue_archive_page.render_to_response(request, extra_context=context)
426         
427         def add_item(self, feed, obj, kwargs=None):
428                 defaults = {
429                         'title': obj.title,
430                         'author_name': ', '.join([author.get_full_name() for author in obj.authors.all()]),
431                         'pubdate': obj.date,
432                         'description': obj.lede or obj.full_text,
433                         'categories': [tag.name for tag in obj.tags.all()]
434                 }
435                 defaults.update(kwargs or {})
436                 super(NewsletterView, self).add_item(feed, obj, defaults)
437         
438         def get_feed(self, feed_type, extra_context, kwargs=None):
439                 title = self.newsletter.title
440                 
441                 defaults = {
442                         'title': title
443                 }
444                 defaults.update(kwargs or {})
445                 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)