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 *
16 class Blog(Entity, Titled):
19 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
20 return Tag.objects.filter(blogentries__blog=self).distinct()
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')}
28 register_value_model(Blog)
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)
41 verbose_name_plural = "blog entries"
44 register_value_model(BlogEntry)
47 class BlogView(MultiView, FeedMultiViewMixin):
48 ENTRY_PERMALINK_STYLE_CHOICES = (
49 ('D', 'Year, month, and day'),
50 ('M', 'Year and month'),
56 blog = models.ForeignKey(Blog, related_name='blogviews')
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)
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()
72 def __unicode__(self):
73 return u'BlogView for %s' % self.blog.title
77 return self.entries_per_page
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:
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)
108 raise ViewCanNotProvideSubpath
110 def get_context(self):
111 return {'blog': self.blog}
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')
120 if self.tag_archive_page:
121 urlpatterns += patterns('',
122 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view)
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')))
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'))),
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')))
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)
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)
147 elif self.entry_permalink_style == 'Y':
148 urlpatterns += patterns('',
149 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
151 elif self.entry_permalink_style == 'B':
152 urlpatterns += patterns('',
153 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
156 urlpatterns = patterns('',
157 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
161 def get_all_entries(self, request, node=None, extra_context=None):
162 return self.blog.entries.all(), extra_context
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:
167 entries = self.blog.entries.all()
169 entries = entries.filter(date__year=year)
171 entries = entries.filter(date__month=month)
173 entries = entries.filter(date__day=day)
175 context = extra_context or {}
176 context.update({'year': year, 'month': month, 'day': day})
177 return entries, context
179 def get_entries_by_tag(self, request, tag_slugs, node=None, extra_context=None):
181 for tag_slug in tag_slugs.replace('+', '/').split('/'):
182 if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
184 tag = self.blog.entry_tags.get(slug=tag_slug)
191 entries = self.blog.entries.all()
193 entries = entries.filter(tags=tag)
195 context = self.get_context()
196 context.update(extra_context or {})
197 context.update({'tags': tags})
199 return entries, context
201 def add_item(self, feed, obj, kwargs=None):
204 'description': obj.excerpt or obj.content,
205 'author_name': obj.author.get_full_name(),
208 defaults.update(kwargs or {})
209 super(BlogView, self).add_item(feed, obj, defaults)
211 def get_feed(self, feed_type, extra_context, kwargs=None):
212 tags = (extra_context or {}).get('tags', None)
213 title = self.blog.title
216 title += " - %s" % ', '.join([tag.name for tag in tags])
221 defaults.update(kwargs or {})
222 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
224 def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
225 entries = self.blog.entries.all()
227 entries = entries.filter(date__year=year)
229 entries = entries.filter(date__month=month)
231 entries = entries.filter(date__day=day)
233 entry = entries.get(slug=slug)
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)
241 def tag_archive_view(self, request, node=None, extra_context=None):
242 if not self.tag_archive_page:
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)
250 class Newsletter(Entity, Titled):
254 register_value_model(Newsletter)
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)
266 get_latest_by = 'date'
268 unique_together = (('newsletter', 'slug'),)
271 register_value_model(NewsletterArticle)
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')
280 ordering = ['-numbering']
281 unique_together = (('newsletter', 'numbering'),)
284 register_value_model(NewsletterIssue)
287 class NewsletterView(MultiView, FeedMultiViewMixin):
288 ARTICLE_PERMALINK_STYLE_CHOICES = (
289 ('D', 'Year, month, and day'),
290 ('M', 'Year and month'),
295 newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
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)
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')
307 feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
308 feeds_enabled = models.BooleanField()
309 list_var = 'articles'
311 def __unicode__(self):
312 return self.newsletter.__unicode__()
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
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')))
336 if self.issue_archive_page:
337 urlpatterns += patterns('',
338 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
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')))
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')))
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')))
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')))
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)
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)
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)
370 urlpatterns += patterns('',
371 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
376 def get_context(self):
377 return {'newsletter': self.newsletter}
379 def get_all_articles(self, request, node, extra_context=None):
380 return self.newsletter.articles.all(), extra_context
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)
385 articles = articles.filter(date__month=month)
387 articles = articles.filter(date__day=day)
390 def get_articles_by_issue(self, request, numbering, node=None, extra_context=None):
392 issue = self.newsletter.issues.get(numbering=numbering)
395 context = extra_context or {}
396 context.update({'issue': issue})
397 return issue.articles.all(), context
399 def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
400 articles = self.newsletter.articles.all()
402 articles = articles.filter(date__year=year)
404 articles = articles.filter(date__month=month)
406 articles = articles.filter(date__day=day)
408 article = articles.get(slug=slug)
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)
416 def issue_archive_view(self, request, node=None, extra_context=None):
417 if not self.issue_archive_page:
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)
424 def add_item(self, feed, obj, kwargs=None):
427 'author_name': ', '.join(obj.authors),
429 'description': obj.lede or obj.full_text,
430 'categories': [tag.name for tag in obj.tags.all()]
432 defaults.update(kwargs or {})
433 super(NewsletterView, self).add_item(feed, obj, defaults)
435 def get_feed(self, feed_type, extra_context, kwargs=None):
436 title = self.newsletter.title
441 defaults.update(kwargs or {})
442 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)