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