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