Explicit declaration of keys for AttributeFields and RelationshipFields is now unnece...
[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.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                 paginator, page, entries = paginate(self.blog.entries.all(), self.entries_per_page, request.GET.get('page', 1))
134                 context = {}
135                 context.update(extra_context or {})
136                 context.update({'blog': self.blog, 'paginator': paginator, 'paginated_page': page, 'entries': entries})
137                 return self.index_page.render_to_response(node, request, extra_context=context)
138         
139         def entry_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
140                 entries = self.blog.entries.all()
141                 if year:
142                         entries = entries.filter(date__year=year)
143                 if month:
144                         entries = entries.filter(date__month=month)
145                 if day:
146                         entries = entries.filter(date__day=day)
147                 try:
148                         entry = entries.get(slug=slug)
149                 except:
150                         raise Http404
151                 context = {}
152                 context.update(extra_context or {})
153                 context.update({'blog': self.blog, 'entry': entry})
154                 return self.entry_page.render_to_response(node, request, extra_context=context)
155         
156         def entry_archive_view(self, request, year=None, month=None, day=None, node=None, extra_context=None):
157                 if not self.entry_archive_page:
158                         raise Http404
159                 entries = self.blog.entries.all()
160                 if year:
161                         entries = entries.filter(date__year=year)
162                 if month:
163                         entries = entries.filter(date__month=month)
164                 if day:
165                         entries = entries.filter(date__day=day)
166                 
167                 paginator, page, entries = paginate(entries, self.entries_per_page, request.GET.get('page', 1))
168                 context = {}
169                 context.update(extra_context or {})
170                 context.update({'blog': self.blog, 'year': year, 'month': month, 'day': day, 'paginator': paginator, 'paginated_page': page, 'entries': entries})
171                 return self.entry_archive_page.render_to_response(node, request, extra_context=context)
172         
173         def tag_view(self, request, tag_slugs, node=None, extra_context=None):
174                 tags = []
175                 for tag_slug in tag_slugs.replace('+', '/').split('/'):
176                         if tag_slug: # ignore blank slugs, handles for multiple consecutive separators (+ or /)
177                                 try:
178                                         tag = self.blog.entry_tags.get(slug=tag_slug)
179                                 except:
180                                         raise Http404
181                                 tags.append(tag)
182                 if len(tags) <= 0:
183                         raise Http404
184                 
185                 entries = self.blog.entries.all()
186                 for tag in tags:
187                         entries = entries.filter(tags=tag)
188                 if entries.count() <= 0:
189                         raise Http404
190                 
191                 paginator, page, entries = paginate(entries, self.entries_per_page, request.GET.get('page', 1))
192                 context = {}
193                 context.update(extra_context or {})
194                 context.update({'blog': self.blog, 'tags': tags, 'paginator': paginator, 'paginated_page': page, 'entries': entries})
195                 return self.tag_page.render_to_response(node, request, extra_context=context)
196         
197         def tag_archive_view(self, request, node=None, extra_context=None):
198                 if not self.tag_archive_page:
199                         raise Http404
200                 context = {}
201                 context.update(extra_context or {})
202                 context.update({'blog': self.blog})
203                 return self.tag_archive_page.render_to_response(node, request, extra_context=context)
204
205
206 class Newsletter(Entity, Titled):
207         pass
208
209
210 register_value_model(Newsletter)
211
212
213 class NewsletterArticle(Entity, Titled):
214         newsletter = models.ForeignKey(Newsletter, related_name='articles')
215         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
216         date = models.DateTimeField(default=datetime.now)
217         lede = models.TextField(null=True, blank=True)
218         full_text = models.TextField()
219         
220         class Meta:
221                 get_latest_by = 'date'
222                 ordering = ['-date']
223                 unique_together = (('newsletter', 'slug'),)
224
225
226 register_value_model(NewsletterArticle)
227
228
229 class NewsletterIssue(Entity, Titled):
230         newsletter = models.ForeignKey(Newsletter, related_name='issues')
231         number = models.PositiveIntegerField()
232         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
233         
234         class Meta:
235                 ordering = ['-number']
236                 unique_together = (('newsletter', 'number'),)
237
238
239 register_value_model(NewsletterIssue)
240
241
242 class NewsletterView(MultiView):
243         ARTICLE_PERMALINK_STYLE_CHOICES = (
244                 ('D', 'Year, month, and day'),
245                 ('M', 'Year and month'),
246                 ('Y', 'Year'),
247                 ('S', 'Slug only')
248         )
249         
250         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
251         
252         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
253         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
254         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
255         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
256         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
257         
258         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
259         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
260         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
261         
262         def get_subpath(self, obj):
263                 if isinstance(obj, NewsletterArticle):
264                         if obj.newsletter == self.newsletter:
265                                 article_view_args = {'slug': obj.slug}
266                                 if self.article_permalink_style in 'DMY':
267                                         article_view_args.update({'year': str(obj.date.year).zfill(4)})
268                                         if self.article_permalink_style in 'DM':
269                                                 article_view_args.update({'month': str(obj.date.month).zfill(2)})
270                                                 if self.article_permalink_style == 'D':
271                                                         article_view_args.update({'day': str(obj.date.day).zfill(2)})
272                                 return reverse(self.article_view, urlconf=self, kwargs=article_view_args)
273                 elif isinstance(obj, NewsletterIssue):
274                         if obj.newsletter == self.newsletter:
275                                 return reverse(self.issue_view, urlconf=self, kwargs={'number': str(obj.number)})
276                 raise ViewCanNotProvideSubpath
277         
278         @property
279         def urlpatterns(self):
280                 base_patterns = patterns('',
281                         url(r'^$', self.index_view),
282                         url((r'^(?:%s)/?$' % self.issue_permalink_base), self.issue_archive_view),
283                         url((r'^(?:%s)/(?P<number>\d+)/?$' % self.issue_permalink_base), self.issue_view)
284                 )
285                 article_patterns = patterns('',
286                         url((r'^(?:%s)/?$' % self.article_permalink_base), self.article_archive_view)
287                 )
288                 if self.article_permalink_style in 'DMY':
289                         article_patterns += patterns('',
290                                 url((r'^(?:%s)/(?P<year>\d{4})/?$' % self.article_permalink_base), self.article_archive_view)
291                         )
292                         if self.article_permalink_style in 'DM':
293                                 article_patterns += patterns('',
294                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/?$' % self.article_permalink_base), self.article_archive_view)
295                                 )
296                                 if self.article_permalink_style == 'D':
297                                         article_patterns += patterns('',
298                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$' % self.article_permalink_base), self.article_archive_view),
299                                                 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)
300                                         )
301                                 else:
302                                         article_patterns += patterns('',
303                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
304                                         )
305                         else:
306                                 article_patterns += patterns('',
307                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
308                                 )
309                 else:
310                         article_patterns += patterns('',
311                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
312                         )
313                 return base_patterns + article_patterns
314         
315         def index_view(self, request, node=None, extra_context=None):
316                 context = {}
317                 context.update(extra_context or {})
318                 context.update({'newsletter': self.newsletter})
319                 return self.index_page.render_to_response(node, request, extra_context=context)
320         
321         def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
322                 articles = self.newsletter.articles.all()
323                 if year:
324                         articles = articles.filter(date__year=year)
325                 if month:
326                         articles = articles.filter(date__month=month)
327                 if day:
328                         articles = articles.filter(date__day=day)
329                 try:
330                         article = articles.get(slug=slug)
331                 except:
332                         raise Http404
333                 context = {}
334                 context.update(extra_context or {})
335                 context.update({'newsletter': self.newsletter, 'article': article})
336                 return self.article_page.render_to_response(node, request, extra_context=context)
337         
338         def article_archive_view(self, request, year=None, month=None, day=None, node=None, extra_context=None):
339                 if not self.article_archive_page:
340                         raise Http404
341                 articles = self.newsletter.articles.all()
342                 if year:
343                         articles = articles.filter(date__year=year)
344                 if month:
345                         articles = articles.filter(date__month=month)
346                 if day:
347                         articles = articles.filter(date__day=day)
348                 context = {}
349                 context.update(extra_context or {})
350                 context.update({'newsletter': self.newsletter, 'year': year, 'month': month, 'day': day, 'articles': articles})
351                 return self.article_archive_page.render_to_response(node, request, extra_context=context)
352         
353         def issue_view(self, request, number, node=None, extra_context=None):
354                 try:
355                         issue = self.newsletter.issues.get(number=number)
356                 except:
357                         raise Http404
358                 context = {}
359                 context.update(extra_context or {})
360                 context.update({'newsletter': self.newsletter, 'issue': issue})
361                 return self.issue_page.render_to_response(node, request, extra_context=context)
362         
363         def issue_archive_view(self, request, node=None, extra_context=None):
364                 if not self.issue_archive_page:
365                         raise Http404
366                 context = {}
367                 context.update(extra_context or {})
368                 context.update({'newsletter': self.newsletter})
369                 return self.issue_archive_page.render_to_response(node, request, extra_context=context)