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