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
14 class Blog(Entity, Titled):
17 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
18 return Tag.objects.filter(blogentries__blog=self).distinct()
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')}
26 register_value_model(Blog)
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)
39 verbose_name_plural = "blog entries"
40 get_latest_by = "date"
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_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)):
94 'year': str(obj.year).zfill(4),
95 'month': str(obj.month).zfill(2),
96 'day': str(obj.day).zfill(2)
98 return 'entries_by_day', [], kwargs
99 raise ViewCanNotProvideSubpath
101 def get_context(self):
102 return {'blog': self.blog}
105 def urlpatterns(self):
106 urlpatterns = patterns('',
107 url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
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'),
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')
116 if self.tag_archive_page:
117 urlpatterns += patterns('',
118 url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view)
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')))
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'))),
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')))
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)
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)
143 elif self.entry_permalink_style == 'Y':
144 urlpatterns += patterns('',
145 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
147 elif self.entry_permalink_style == 'B':
148 urlpatterns += patterns('',
149 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
152 urlpatterns = patterns('',
153 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
157 def get_all_entries(self, request, extra_context=None):
158 return self.blog.entries.all(), extra_context
160 def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
161 if not self.entry_archive_page:
163 entries = self.blog.entries.all()
165 entries = entries.filter(date__year=year)
167 entries = entries.filter(date__month=month)
169 entries = entries.filter(date__day=day)
171 context = extra_context or {}
172 context.update({'year': year, 'month': month, 'day': day})
173 return entries, context
175 def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
177 for tag_slug in tag_slugs.replace('+', '/').split('/'):
178 if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
180 tag = self.blog.entry_tags.get(slug=tag_slug)
187 entries = self.blog.entries.all()
189 entries = entries.filter(tags=tag)
191 context = self.get_context()
192 context.update(extra_context or {})
193 context.update({'tags': tags})
195 return entries, context
197 def add_item(self, feed, obj, kwargs=None):
200 'description': obj.excerpt or obj.content,
201 'author_name': obj.author.get_full_name(),
204 defaults.update(kwargs or {})
205 super(BlogView, self).add_item(feed, obj, defaults)
207 def get_feed(self, feed_type, extra_context, kwargs=None):
208 tags = (extra_context or {}).get('tags', None)
209 title = self.blog.title
212 title += " - %s" % ', '.join([tag.name for tag in tags])
217 defaults.update(kwargs or {})
218 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
220 def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
221 entries = self.blog.entries.all()
223 entries = entries.filter(date__year=year)
225 entries = entries.filter(date__month=month)
227 entries = entries.filter(date__day=day)
229 entry = entries.get(slug=slug)
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)
237 def tag_archive_view(self, request, extra_context=None):
238 if not self.tag_archive_page:
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)
246 class Newsletter(Entity, Titled):
250 register_value_model(Newsletter)
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)
262 get_latest_by = 'date'
264 unique_together = (('newsletter', 'slug'),)
267 register_value_model(NewsletterArticle)
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')
276 ordering = ['-numbering']
277 unique_together = (('newsletter', 'numbering'),)
280 register_value_model(NewsletterIssue)
283 class NewsletterView(MultiView, FeedMultiViewMixin):
284 ARTICLE_PERMALINK_STYLE_CHOICES = (
285 ('D', 'Year, month, and day'),
286 ('M', 'Year and month'),
291 newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
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)
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')
303 feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
304 feeds_enabled = models.BooleanField()
305 list_var = 'articles'
307 def __unicode__(self):
308 return self.newsletter.__unicode__()
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)):
326 'year': str(obj.year).zfill(4),
327 'month': str(obj.month).zfill(2),
328 'day': str(obj.day).zfill(2)
330 return 'articles_by_day', [], kwargs
331 raise ViewCanNotProvideSubpath
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')))
339 if self.issue_archive_page:
340 urlpatterns += patterns('',
341 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view)
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')))
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')))
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')))
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')))
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)
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)
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)
373 urlpatterns += patterns('',
374 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
379 def get_context(self):
380 return {'newsletter': self.newsletter}
382 def get_all_articles(self, request, extra_context=None):
383 return self.newsletter.articles.all(), extra_context
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)
388 articles = articles.filter(date__month=month)
390 articles = articles.filter(date__day=day)
393 def get_articles_by_issue(self, request, numbering, extra_context=None):
395 issue = self.newsletter.issues.get(numbering=numbering)
396 except NewsletterIssue.DoesNotExist:
398 context = extra_context or {}
399 context.update({'issue': issue})
400 return issue.articles.all(), context
402 def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
403 articles = self.newsletter.articles.all()
405 articles = articles.filter(date__year=year)
407 articles = articles.filter(date__month=month)
409 articles = articles.filter(date__day=day)
411 article = articles.get(slug=slug)
412 except NewsletterArticle.DoesNotExist:
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)
419 def issue_archive_view(self, request, extra_context=None):
420 if not self.issue_archive_page:
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)
427 def add_item(self, feed, obj, kwargs=None):
430 'author_name': ', '.join([author.get_full_name() for author in obj.authors.all()]),
432 'description': obj.lede or obj.full_text,
433 'categories': [tag.name for tag in obj.tags.all()]
435 defaults.update(kwargs or {})
436 super(NewsletterView, self).add_item(feed, obj, defaults)
438 def get_feed(self, feed_type, extra_context, kwargs=None):
439 title = self.newsletter.title
444 defaults.update(kwargs or {})
445 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)