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
15 class Blog(Entity, Titled):
18 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
19 return Tag.objects.filter(blogentries__blog=self).distinct()
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')}
27 register_value_model(Blog)
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)
40 verbose_name_plural = "blog entries"
43 register_value_model(BlogEntry)
46 class BlogView(MultiView, FeedMultiViewMixin):
47 ENTRY_PERMALINK_STYLE_CHOICES = (
48 ('D', 'Year, month, and day'),
49 ('M', 'Year and month'),
55 blog = models.ForeignKey(Blog, related_name='blogviews')
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)
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()
71 def __unicode__(self):
72 return u'BlogView for %s' % self.blog.title
76 return self.entries_per_page
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:
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)
107 raise ViewCanNotProvideSubpath
109 def get_context(self):
110 return {'blog': self.blog}
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')
119 if self.tag_archive_page:
120 urlpatterns += patterns('',
121 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view)
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')))
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'))),
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')))
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)
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)
146 elif self.entry_permalink_style == 'Y':
147 urlpatterns += patterns('',
148 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
150 elif self.entry_permalink_style == 'B':
151 urlpatterns += patterns('',
152 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
155 urlpatterns = patterns('',
156 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
160 def get_all_entries(self, request, node=None, extra_context=None):
161 return self.blog.entries.all(), extra_context
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:
166 entries = self.blog.entries.all()
168 entries = entries.filter(date__year=year)
170 entries = entries.filter(date__month=month)
172 entries = entries.filter(date__day=day)
174 context = extra_context or {}
175 context.update({'year': year, 'month': month, 'day': day})
176 return entries, context
178 def get_entries_by_tag(self, request, tag_slugs, node=None, extra_context=None):
180 for tag_slug in tag_slugs.replace('+', '/').split('/'):
181 if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
183 tag = self.blog.entry_tags.get(slug=tag_slug)
190 entries = self.blog.entries.all()
192 entries = entries.filter(tags=tag)
194 context = self.get_context()
195 context.update(extra_context or {})
196 context.update({'tags': tags})
198 return entries, context
200 def add_item(self, feed, obj, kwargs=None):
203 'description': obj.excerpt or obj.content,
204 'author_name': obj.author.get_full_name(),
207 defaults.update(kwargs or {})
208 super(BlogView, self).add_item(feed, obj, defaults)
210 def get_feed(self, feed_type, extra_context, kwargs=None):
211 tags = (extra_context or {}).get('tags', None)
212 title = self.blog.title
215 title += " - %s" % ', '.join([tag.name for tag in tags])
220 defaults.update(kwargs or {})
221 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
223 def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
224 entries = self.blog.entries.all()
226 entries = entries.filter(date__year=year)
228 entries = entries.filter(date__month=month)
230 entries = entries.filter(date__day=day)
232 entry = entries.get(slug=slug)
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)
240 def tag_archive_view(self, request, node=None, extra_context=None):
241 if not self.tag_archive_page:
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)
249 class Newsletter(Entity, Titled):
253 register_value_model(Newsletter)
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)
265 get_latest_by = 'date'
267 unique_together = (('newsletter', 'slug'),)
270 register_value_model(NewsletterArticle)
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')
279 ordering = ['-numbering']
280 unique_together = (('newsletter', 'numbering'),)
283 register_value_model(NewsletterIssue)
286 class NewsletterView(MultiView, FeedMultiViewMixin):
287 ARTICLE_PERMALINK_STYLE_CHOICES = (
288 ('D', 'Year, month, and day'),
289 ('M', 'Year and month'),
294 newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
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)
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')
306 feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
307 feeds_enabled = models.BooleanField()
308 list_var = 'articles'
310 def __unicode__(self):
311 return self.newsletter.__unicode__()
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
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')))
335 if self.issue_archive_page:
336 urlpatterns += patterns('',
337 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
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')))
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')))
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')))
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')))
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)
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)
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)
369 urlpatterns += patterns('',
370 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
375 def get_context(self):
376 return {'newsletter': self.newsletter}
378 def get_all_articles(self, request, node, extra_context=None):
379 return self.newsletter.articles.all(), extra_context
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)
384 articles = articles.filter(date__month=month)
386 articles = articles.filter(date__day=day)
389 def get_articles_by_issue(self, request, numbering, node=None, extra_context=None):
391 issue = self.newsletter.issues.get(numbering=numbering)
394 context = extra_context or {}
395 context.update({'issue': issue})
396 return issue.articles.all(), context
398 def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
399 articles = self.newsletter.articles.all()
401 articles = articles.filter(date__year=year)
403 articles = articles.filter(date__month=month)
405 articles = articles.filter(date__day=day)
407 article = articles.get(slug=slug)
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)
415 def issue_archive_view(self, request, node=None, extra_context=None):
416 if not self.issue_archive_page:
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)
423 def add_item(self, feed, obj, kwargs=None):
426 'author_name': ', '.join(obj.authors),
428 'description': obj.lede or obj.full_text,
429 'categories': [tag.name for tag in obj.tags.all()]
431 defaults.update(kwargs or {})
432 super(NewsletterView, self).add_item(feed, obj, defaults)
434 def get_feed(self, feed_type, extra_context, kwargs=None):
435 title = self.newsletter.title
440 defaults.update(kwargs or {})
441 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)