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