Fixed a grave error wherein Node did not have a TreeManager as its default manager...
[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
6 from django.core.urlresolvers import reverse
7 from django.http import Http404, HttpResponse
8 from datetime import datetime
9 from philo.contrib.penfield.utils import paginate
10 from philo.contrib.penfield.validators import validate_pagination_count
11
12
13 class Blog(Entity, Titled):
14         @property
15         def entry_tags(self):
16                 """ Returns a QuerySet of Tags that are used on any entries in this blog. """
17                 return Tag.objects.filter(blogentries__blog=self).distinct()
18         
19         @property
20         def entry_dates(self):
21                 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')}
22                 return dates
23
24
25 register_value_model(Blog)
26
27
28 class BlogEntry(Entity, Titled):
29         blog = models.ForeignKey(Blog, related_name='entries')
30         author = models.ForeignKey(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='blogentries')
31         date = models.DateTimeField(default=datetime.now)
32         content = models.TextField()
33         excerpt = models.TextField(blank=True, null=True)
34         tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
35         
36         class Meta:
37                 ordering = ['-date']
38                 verbose_name_plural = "blog entries"
39
40
41 register_value_model(BlogEntry)
42
43
44 class BlogView(MultiView):
45         ENTRY_PERMALINK_STYLE_CHOICES = (
46                 ('D', 'Year, month, and day'),
47                 ('M', 'Year and month'),
48                 ('Y', 'Year'),
49                 ('B', 'Custom base'),
50                 ('N', 'No base')
51         )
52         
53         blog = models.ForeignKey(Blog, related_name='blogviews')
54         
55         index_page = models.ForeignKey(Page, related_name='blog_index_related')
56         entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
57         entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
58         tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
59         tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
60         entries_per_page = models.IntegerField(blank=True, validators=[validate_pagination_count], null=True)
61         
62         entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
63         entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
64         tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
65         
66         def __unicode__(self):
67                 return u'BlogView for %s' % self.blog.title
68         
69         def get_subpath(self, obj):
70                 if isinstance(obj, BlogEntry):
71                         if obj.blog == self.blog:
72                                 entry_view_args = {'slug': obj.slug}
73                                 if self.entry_permalink_style in 'DMY':
74                                         entry_view_args.update({'year': str(obj.date.year).zfill(4)})
75                                         if self.entry_permalink_style in 'DM':
76                                                 entry_view_args.update({'month': str(obj.date.month).zfill(2)})
77                                                 if self.entry_permalink_style == 'D':
78                                                         entry_view_args.update({'day': str(obj.date.day).zfill(2)})
79                                 return reverse(self.entry_view, urlconf=self, kwargs=entry_view_args)
80                 elif isinstance(obj, Tag):
81                         if obj in self.blog.entry_tags:
82                                 return reverse(self.tag_view, urlconf=self, kwargs={'tag_slugs': obj.slug})
83                 elif isinstance(obj, (str, unicode)):
84                         split_obj = obj.split(':')
85                         if len(split_obj) > 1:
86                                 entry_archive_view_args = {}
87                                 if split_obj[0].lower() == 'archives':
88                                         entry_archive_view_args.update({'year': str(int(split_obj[1])).zfill(4)})
89                                         if len(split_obj) > 2:
90                                                 entry_archive_view_args.update({'month': str(int(split_obj[2])).zfill(2)})
91                                                 if len(split_obj) > 3:
92                                                         entry_archive_view_args.update({'day': str(int(split_obj[3])).zfill(2)})
93                                         return reverse(self.entry_archive_view, urlconf=self, kwargs=entry_archive_view_args)
94                 raise ViewCanNotProvideSubpath
95         
96         @property
97         def urlpatterns(self):
98                 base_patterns = patterns('',
99                         url(r'^$', self.index_view),
100                         url((r'^(?:%s)/?$' % self.tag_permalink_base), self.tag_archive_view),
101                         url((r'^(?:%s)/(?P<tag_slugs>[-\w]+[-+/\w]*)/?$' % self.tag_permalink_base), self.tag_view)
102                 )
103                 if self.entry_permalink_style == 'D':
104                         entry_patterns = patterns('',
105                                 url(r'^(?P<year>\d{4})/?$', self.entry_archive_view),
106                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/?$', self.entry_archive_view),
107                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$', self.entry_archive_view),
108                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
109                         )
110                 elif self.entry_permalink_style == 'M':
111                         entry_patterns = patterns('',
112                                 url(r'^(?P<year>\d{4})/?$', self.entry_archive_view),
113                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/?$', self.entry_archive_view),
114                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$', self.entry_view)
115                         )
116                 elif self.entry_permalink_style == 'Y':
117                         entry_patterns = patterns('',
118                                 url(r'^(?P<year>\d{4})/?$', self.entry_archive_view),
119                                 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)/?$', self.entry_view)
120                         )
121                 elif self.entry_permalink_style == 'B':
122                         entry_patterns = patterns('',
123                                 url((r'^(?:%s)/?$' % self.entry_permalink_base), self.entry_archive_view),
124                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.entry_permalink_base), self.entry_view)
125                         )
126                 else:
127                         entry_patterns = patterns('',
128                                 url(r'^(?P<slug>[-\w]+)/?$', self.entry_view)
129                         )
130                 return base_patterns + entry_patterns
131         
132         def index_view(self, request, node=None, extra_context=None):
133                 entries = self.blog.entries.all()
134                 if self.entries_per_page:
135                         paginated_page = paginate(request, entries, self.entries_per_page)
136                         entries = paginated_page.object_list
137                 else:
138                         paginated_page = None
139                 context = {}
140                 context.update(extra_context or {})
141                 context.update({'blog': self.blog, 'entries': entries, 'paginated_page': paginated_page})
142                 return self.index_page.render_to_response(node, request, extra_context=context)
143         
144         def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
145                 entries = self.blog.entries.all()
146                 if year:
147                         entries = entries.filter(date__year=year)
148                 if month:
149                         entries = entries.filter(date__month=month)
150                 if day:
151                         entries = entries.filter(date__day=day)
152                 try:
153                         entry = entries.get(slug=slug)
154                 except:
155                         raise Http404
156                 context = {}
157                 context.update(extra_context or {})
158                 context.update({'blog': self.blog, 'entry': entry})
159                 return self.entry_page.render_to_response(node, request, extra_context=context)
160         
161         def entry_archive_view(self, request, year=None, month=None, day=None, node=None, extra_context=None):
162                 if not self.entry_archive_page:
163                         raise Http404
164                 entries = self.blog.entries.all()
165                 if year:
166                         entries = entries.filter(date__year=year)
167                 if month:
168                         entries = entries.filter(date__month=month)
169                 if day:
170                         entries = entries.filter(date__day=day)
171                 if self.entries_per_page:
172                         paginated_page = paginate(request, entries, self.entries_per_page)
173                         entries = paginated_page.object_list
174                 else:
175                         paginated_page = None
176                 context = {}
177                 context.update(extra_context or {})
178                 context.update({'blog': self.blog, 'year': year, 'month': month, 'day': day, 'entries': entries, 'paginated_page': paginated_page})
179                 return self.entry_archive_page.render_to_response(node, request, extra_context=context)
180         
181         def tag_view(self, request, tag_slugs, node=None, extra_context=None):
182                 tags = []
183                 for tag_slug in tag_slugs.replace('+', '/').split('/'):
184                         if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
185                                 try:
186                                         tag = self.blog.entry_tags.get(slug=tag_slug)
187                                 except:
188                                         raise Http404
189                                 tags.append(tag)
190                 if len(tags) <= 0:
191                         raise Http404
192                 
193                 entries = self.blog.entries.all()
194                 for tag in tags:
195                         entries = entries.filter(tags=tag)
196                 if entries.count() <= 0:
197                         raise Http404
198                 
199                 if self.entries_per_page:
200                         paginated_page = paginate(request, entries, self.entries_per_page)
201                         entries = paginated_page.object_list
202                 else:
203                         paginated_page = None
204                 context = {}
205                 context.update(extra_context or {})
206                 context.update({'blog': self.blog, 'tags': tags, 'entries': entries, 'paginated_page': paginated_page})
207                 return self.tag_page.render_to_response(node, request, extra_context=context)
208         
209         def tag_archive_view(self, request, node=None, extra_context=None):
210                 if not self.tag_archive_page:
211                         raise Http404
212                 context = {}
213                 context.update(extra_context or {})
214                 context.update({'blog': self.blog})
215                 return self.tag_archive_page.render_to_response(node, request, extra_context=context)
216
217
218 class Newsletter(Entity, Titled):
219         pass
220
221
222 register_value_model(Newsletter)
223
224
225 class NewsletterArticle(Entity, Titled):
226         newsletter = models.ForeignKey(Newsletter, related_name='articles')
227         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
228         date = models.DateTimeField(default=datetime.now)
229         lede = models.TextField(null=True, blank=True)
230         full_text = models.TextField()
231         
232         class Meta:
233                 get_latest_by = 'date'
234                 ordering = ['-date']
235                 unique_together = (('newsletter', 'slug'),)
236
237
238 register_value_model(NewsletterArticle)
239
240
241 class NewsletterIssue(Entity, Titled):
242         newsletter = models.ForeignKey(Newsletter, related_name='issues')
243         number = models.PositiveIntegerField()
244         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
245         
246         class Meta:
247                 ordering = ['-number']
248                 unique_together = (('newsletter', 'number'),)
249
250
251 register_value_model(NewsletterIssue)
252
253
254 class NewsletterView(MultiView):
255         ARTICLE_PERMALINK_STYLE_CHOICES = (
256                 ('D', 'Year, month, and day'),
257                 ('M', 'Year and month'),
258                 ('Y', 'Year'),
259                 ('S', 'Slug only')
260         )
261         
262         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
263         
264         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
265         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
266         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
267         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
268         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
269         
270         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
271         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
272         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
273         
274         def get_subpath(self, obj):
275                 if isinstance(obj, NewsletterArticle):
276                         if obj.newsletter == self.newsletter:
277                                 article_view_args = {'slug': obj.slug}
278                                 if self.article_permalink_style in 'DMY':
279                                         article_view_args.update({'year': str(obj.date.year).zfill(4)})
280                                         if self.article_permalink_style in 'DM':
281                                                 article_view_args.update({'month': str(obj.date.month).zfill(2)})
282                                                 if self.article_permalink_style == 'D':
283                                                         article_view_args.update({'day': str(obj.date.day).zfill(2)})
284                                 return reverse(self.article_view, urlconf=self, kwargs=article_view_args)
285                 elif isinstance(obj, NewsletterIssue):
286                         if obj.newsletter == self.newsletter:
287                                 return reverse(self.issue_view, urlconf=self, kwargs={'number': str(obj.number)})
288                 raise ViewCanNotProvideSubpath
289         
290         @property
291         def urlpatterns(self):
292                 base_patterns = patterns('',
293                         url(r'^$', self.index_view),
294                         url((r'^(?:%s)/?$' % self.issue_permalink_base), self.issue_archive_view),
295                         url((r'^(?:%s)/(?P<number>\d+)/?$' % self.issue_permalink_base), self.issue_view)
296                 )
297                 article_patterns = patterns('',
298                         url((r'^(?:%s)/?$' % self.article_permalink_base), self.article_archive_view)
299                 )
300                 if self.article_permalink_style in 'DMY':
301                         article_patterns += patterns('',
302                                 url((r'^(?:%s)/(?P<year>\d{4})/?$' % self.article_permalink_base), self.article_archive_view)
303                         )
304                         if self.article_permalink_style in 'DM':
305                                 article_patterns += patterns('',
306                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/?$' % self.article_permalink_base), self.article_archive_view)
307                                 )
308                                 if self.article_permalink_style == 'D':
309                                         article_patterns += patterns('',
310                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$' % self.article_permalink_base), self.article_archive_view),
311                                                 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)
312                                         )
313                                 else:
314                                         article_patterns += patterns('',
315                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
316                                         )
317                         else:
318                                 article_patterns += patterns('',
319                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
320                                 )
321                 else:
322                         article_patterns += patterns('',
323                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
324                         )
325                 return base_patterns + article_patterns
326         
327         def index_view(self, request, node=None, extra_context=None):
328                 context = {}
329                 context.update(extra_context or {})
330                 context.update({'newsletter': self.newsletter})
331                 return self.index_page.render_to_response(node, request, extra_context=context)
332         
333         def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
334                 articles = self.newsletter.articles.all()
335                 if year:
336                         articles = articles.filter(date__year=year)
337                 if month:
338                         articles = articles.filter(date__month=month)
339                 if day:
340                         articles = articles.filter(date__day=day)
341                 try:
342                         article = articles.get(slug=slug)
343                 except:
344                         raise Http404
345                 context = {}
346                 context.update(extra_context or {})
347                 context.update({'newsletter': self.newsletter, 'article': article})
348                 return self.article_page.render_to_response(node, request, extra_context=context)
349         
350         def article_archive_view(self, request, year=None, month=None, day=None, node=None, extra_context=None):
351                 if not self.article_archive_page:
352                         raise Http404
353                 articles = self.newsletter.articles.all()
354                 if year:
355                         articles = articles.filter(date__year=year)
356                 if month:
357                         articles = articles.filter(date__month=month)
358                 if day:
359                         articles = articles.filter(date__day=day)
360                 context = {}
361                 context.update(extra_context or {})
362                 context.update({'newsletter': self.newsletter, 'year': year, 'month': month, 'day': day, 'articles': articles})
363                 return self.article_archive_page.render_to_response(node, request, extra_context=context)
364         
365         def issue_view(self, request, number, node=None, extra_context=None):
366                 try:
367                         issue = self.newsletter.issues.get(number=number)
368                 except:
369                         raise Http404
370                 context = {}
371                 context.update(extra_context or {})
372                 context.update({'newsletter': self.newsletter, 'issue': issue})
373                 return self.issue_page.render_to_response(node, request, extra_context=context)
374         
375         def issue_archive_view(self, request, node=None, extra_context=None):
376                 if not self.issue_archive_page:
377                         raise Http404
378                 context = {}
379                 context.update(extra_context or {})
380                 context.update({'newsletter': self.newsletter})
381                 return self.issue_archive_page.render_to_response(node, request, extra_context=context)