1 from django.conf import settings
2 from django.conf.urls.defaults import url, patterns, include
3 from django.db import models
4 from django.http import Http404
5 from django.template import loader, Context
6 from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
7 from datetime import date, datetime
8 from philo.contrib.penfield.utils import FeedMultiViewMixin
9 from philo.contrib.penfield.validators import validate_pagination_count
10 from philo.exceptions import ViewCanNotProvideSubpath
11 from philo.models import Tag, Titled, Entity, MultiView, Page, register_value_model, TemplateField
12 from philo.utils import paginate
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=None)
34 content = models.TextField()
35 excerpt = models.TextField(blank=True, null=True)
36 tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
38 def save(self, *args, **kwargs):
40 self.date = datetime.now()
41 super(BlogEntry, self).save(*args, **kwargs)
45 verbose_name_plural = "blog entries"
46 get_latest_by = "date"
49 register_value_model(BlogEntry)
52 class BlogView(MultiView, FeedMultiViewMixin):
53 ENTRY_PERMALINK_STYLE_CHOICES = (
54 ('D', 'Year, month, and day'),
55 ('M', 'Year and month'),
61 blog = models.ForeignKey(Blog, related_name='blogviews')
63 index_page = models.ForeignKey(Page, related_name='blog_index_related')
64 entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
65 entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
66 tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
67 tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
68 entries_per_page = models.IntegerField(blank=True, validators=[validate_pagination_count], null=True)
70 entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
71 entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
72 tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
73 feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
74 feeds_enabled = models.BooleanField()
77 def __unicode__(self):
78 return u'BlogView for %s' % self.blog.title
82 return self.entries_per_page
84 def get_reverse_params(self, obj):
85 if isinstance(obj, BlogEntry):
86 if obj.blog == self.blog:
87 kwargs = {'slug': obj.slug}
88 if self.entry_permalink_style in 'DMY':
89 kwargs.update({'year': str(obj.date.year).zfill(4)})
90 if self.entry_permalink_style in 'DM':
91 kwargs.update({'month': str(obj.date.month).zfill(2)})
92 if self.entry_permalink_style == 'D':
93 kwargs.update({'day': str(obj.date.day).zfill(2)})
94 return self.entry_view, [], kwargs
95 elif isinstance(obj, Tag):
96 if obj in self.get_tag_queryset():
97 return 'entries_by_tag', [], {'tag_slugs': obj.slug}
98 elif isinstance(obj, (date, datetime)):
100 'year': str(obj.year).zfill(4),
101 'month': str(obj.month).zfill(2),
102 'day': str(obj.day).zfill(2)
104 return 'entries_by_day', [], kwargs
105 raise ViewCanNotProvideSubpath
108 def urlpatterns(self):
109 urlpatterns = patterns('',
110 url(r'^', include(self.feed_patterns(self.get_all_entries, self.index_page, 'index'))),
112 if self.feeds_enabled:
113 urlpatterns += patterns('',
114 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'),
116 urlpatterns += patterns('',
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, 'tag_archive')
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_context(self):
161 return {'blog': self.blog}
163 def get_entry_queryset(self):
164 return self.blog.entries.all()
166 def get_tag_queryset(self):
167 return self.blog.entry_tags
169 def get_all_entries(self, request, extra_context=None):
170 return self.get_entry_queryset(), extra_context
172 def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
173 if not self.entry_archive_page:
175 entries = self.get_entry_queryset()
177 entries = entries.filter(date__year=year)
179 entries = entries.filter(date__month=month)
181 entries = entries.filter(date__day=day)
183 context = extra_context or {}
184 context.update({'year': year, 'month': month, 'day': day})
185 return entries, context
187 def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
188 tag_slugs = tag_slugs.replace('+', '/').split('/')
189 tags = self.get_tag_queryset().filter(slug__in=tag_slugs)
194 # Raise a 404 on an incorrect slug.
195 found_slugs = [tag.slug for tag in tags]
196 for slug in tag_slugs:
197 if slug and slug not in found_slugs:
200 entries = self.get_entry_queryset()
202 entries = entries.filter(tags=tag)
204 context = extra_context or {}
205 context.update({'tags': tags})
207 return entries, context
209 def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
210 entries = self.get_entry_queryset()
212 entries = entries.filter(date__year=year)
214 entries = entries.filter(date__month=month)
216 entries = entries.filter(date__day=day)
218 entry = entries.get(slug=slug)
221 context = self.get_context()
222 context.update(extra_context or {})
223 context.update({'entry': entry})
224 return self.entry_page.render_to_response(request, extra_context=context)
226 def tag_archive_view(self, request, extra_context=None):
227 if not self.tag_archive_page:
229 context = self.get_context()
230 context.update(extra_context or {})
232 'tags': self.get_tag_queryset()
234 return self.tag_archive_page.render_to_response(request, extra_context=context)
236 def add_item(self, feed, obj, kwargs=None):
237 title = loader.get_template("penfield/feeds/blog_entry/title.html")
238 description = loader.get_template("penfield/feeds/blog_entry/description.html")
240 'title': title.render(Context({'entry': obj})),
241 'description': description.render(Context({'entry': obj})),
242 'author_name': obj.author.get_full_name(),
245 defaults.update(kwargs or {})
246 super(BlogView, self).add_item(feed, obj, defaults)
248 def get_feed(self, feed_type, extra_context, kwargs=None):
249 tags = (extra_context or {}).get('tags', None)
250 title = self.blog.title
253 title += " - %s" % ', '.join([tag.name for tag in tags])
258 defaults.update(kwargs or {})
259 return super(BlogView, self).get_feed(feed_type, extra_context, defaults)
262 class Newsletter(Entity, Titled):
266 register_value_model(Newsletter)
269 class NewsletterArticle(Entity, Titled):
270 newsletter = models.ForeignKey(Newsletter, related_name='articles')
271 authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
272 date = models.DateTimeField(default=None)
273 lede = TemplateField(null=True, blank=True, verbose_name='Summary')
274 full_text = TemplateField(db_index=True)
275 tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
277 def save(self, *args, **kwargs):
278 if self.date is None:
279 self.date = datetime.now()
280 super(NewsletterArticle, self).save(*args, **kwargs)
283 get_latest_by = 'date'
285 unique_together = (('newsletter', 'slug'),)
288 register_value_model(NewsletterArticle)
291 class NewsletterIssue(Entity, Titled):
292 newsletter = models.ForeignKey(Newsletter, related_name='issues')
293 numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
294 articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
297 ordering = ['-numbering']
298 unique_together = (('newsletter', 'numbering'),)
301 register_value_model(NewsletterIssue)
304 class NewsletterView(MultiView, FeedMultiViewMixin):
305 ARTICLE_PERMALINK_STYLE_CHOICES = (
306 ('D', 'Year, month, and day'),
307 ('M', 'Year and month'),
312 newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
314 index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
315 article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
316 article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
317 issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
318 issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
320 article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
321 article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
322 issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
324 feed_suffix = models.CharField(max_length=255, blank=False, default=FeedMultiViewMixin.feed_suffix)
325 feeds_enabled = models.BooleanField()
326 list_var = 'articles'
328 def __unicode__(self):
329 return self.newsletter.__unicode__()
331 def get_reverse_params(self, obj):
332 if isinstance(obj, NewsletterArticle):
333 if obj.newsletter == self.newsletter:
334 kwargs = {'slug': obj.slug}
335 if self.article_permalink_style in 'DMY':
336 kwargs.update({'year': str(obj.date.year).zfill(4)})
337 if self.article_permalink_style in 'DM':
338 kwargs.update({'month': str(obj.date.month).zfill(2)})
339 if self.article_permalink_style == 'D':
340 kwargs.update({'day': str(obj.date.day).zfill(2)})
341 return self.article_view, [], kwargs
342 elif isinstance(obj, NewsletterIssue):
343 if obj.newsletter == self.newsletter:
344 return 'issue', [], {'numbering': obj.numbering}
345 elif isinstance(obj, (date, datetime)):
347 'year': str(obj.year).zfill(4),
348 'month': str(obj.month).zfill(2),
349 'day': str(obj.day).zfill(2)
351 return 'articles_by_day', [], kwargs
352 raise ViewCanNotProvideSubpath
355 def urlpatterns(self):
356 urlpatterns = patterns('',
357 url(r'^', include(self.feed_patterns(self.get_all_articles, self.index_page, 'index'))),
358 url(r'^(?:%s)/(?P<numbering>.+)/' % self.issue_permalink_base, include(self.feed_patterns(self.get_articles_by_issue, self.issue_page, 'issue')))
360 if self.issue_archive_page:
361 urlpatterns += patterns('',
362 url(r'^(?:%s)/$' % self.issue_permalink_base, self.issue_archive_view, 'issue_archive')
364 if self.article_archive_page:
365 urlpatterns += patterns('',
366 url(r'^(?:%s)/' % self.article_permalink_base, include(self.feed_patterns(self.get_all_articles, self.article_archive_page, 'articles')))
368 if self.article_permalink_style in 'DMY':
369 urlpatterns += patterns('',
370 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')))
372 if self.article_permalink_style in 'DM':
373 urlpatterns += patterns('',
374 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')))
376 if self.article_permalink_style == 'D':
377 urlpatterns += patterns('',
378 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')))
381 if self.article_permalink_style == 'Y':
382 urlpatterns += patterns('',
383 url(r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
385 elif self.article_permalink_style == 'M':
386 urlpatterns += patterns('',
387 url(r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)/$' % self.article_permalink_base, self.article_view)
389 elif self.article_permalink_style == 'D':
390 urlpatterns += patterns('',
391 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)
394 urlpatterns += patterns('',
395 url(r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base, self.article_view)
400 def get_context(self):
401 return {'newsletter': self.newsletter}
403 def get_article_queryset(self):
404 return self.newsletter.articles.all()
406 def get_issue_queryset(self):
407 return self.newsletter.issues.all()
409 def get_all_articles(self, request, extra_context=None):
410 return self.get_article_queryset(), extra_context
412 def get_articles_by_ymd(self, request, year, month=None, day=None, extra_context=None):
413 articles = self.get_article_queryset().filter(date__year=year)
415 articles = articles.filter(date__month=month)
417 articles = articles.filter(date__day=day)
418 return articles, extra_context
420 def get_articles_by_issue(self, request, numbering, extra_context=None):
422 issue = self.get_issue_queryset().get(numbering=numbering)
423 except NewsletterIssue.DoesNotExist:
425 context = extra_context or {}
426 context.update({'issue': issue})
427 return self.get_article_queryset().filter(issues=issue), context
429 def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
430 articles = self.get_article_queryset()
432 articles = articles.filter(date__year=year)
434 articles = articles.filter(date__month=month)
436 articles = articles.filter(date__day=day)
438 article = articles.get(slug=slug)
439 except NewsletterArticle.DoesNotExist:
441 context = self.get_context()
442 context.update(extra_context or {})
443 context.update({'article': article})
444 return self.article_page.render_to_response(request, extra_context=context)
446 def issue_archive_view(self, request, extra_context):
447 if not self.issue_archive_page:
449 context = self.get_context()
450 context.update(extra_context or {})
452 'issues': self.get_issue_queryset()
454 return self.issue_archive_page.render_to_response(request, extra_context=context)
456 def add_item(self, feed, obj, kwargs=None):
457 title = loader.get_template("penfield/feeds/newsletter_article/title.html")
458 description = loader.get_template("penfield/feeds/newsletter_article/description.html")
460 'title': title.render(Context({'article': obj})),
461 'author_name': ', '.join([author.get_full_name() for author in obj.authors.all()]),
463 'description': description.render(Context({'article': obj})),
464 'categories': [tag.name for tag in obj.tags.all()]
466 defaults.update(kwargs or {})
467 super(NewsletterView, self).add_item(feed, obj, defaults)
469 def get_feed(self, feed_type, extra_context, kwargs=None):
470 title = self.newsletter.title
475 defaults.update(kwargs or {})
476 return super(NewsletterView, self).get_feed(feed_type, extra_context, defaults)