Initial implementation of AttributeField and RelationshipField.
[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 register_value_model(Newsletter)
207
208
209 class NewsletterArticle(Entity, Titled):
210         newsletter = models.ForeignKey(Newsletter, related_name='articles')
211         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
212         date = models.DateTimeField(default=datetime.now)
213         lede = models.TextField(null=True, blank=True)
214         full_text = models.TextField()
215         
216         class Meta:
217                 ordering = ['-date']
218                 unique_together = (('newsletter', 'slug'),)
219
220
221 register_value_model(NewsletterArticle)
222
223
224 class NewsletterIssue(Entity, Titled):
225         newsletter = models.ForeignKey(Newsletter, related_name='issues')
226         number = models.PositiveIntegerField()
227         articles = models.ManyToManyField(NewsletterArticle)
228         
229         class Meta:
230                 ordering = ['-number']
231                 unique_together = (('newsletter', 'number'),)
232
233
234 register_value_model(NewsletterIssue)
235
236
237 class NewsletterView(MultiView):
238         ARTICLE_PERMALINK_STYLE_CHOICES = (
239                 ('D', 'Year, month, and day'),
240                 ('M', 'Year and month'),
241                 ('Y', 'Year'),
242                 ('S', 'Slug only')
243         )
244         
245         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
246         
247         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
248         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
249         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
250         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
251         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
252         
253         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
254         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
255         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
256         
257         def get_subpath(self, obj):
258                 if isinstance(obj, NewsletterArticle):
259                         if obj.newsletter == self.newsletter:
260                                 article_view_args = {'slug': obj.slug}
261                                 if self.article_permalink_style in 'DMY':
262                                         article_view_args.update({'year': str(obj.date.year).zfill(4)})
263                                         if self.article_permalink_style in 'DM':
264                                                 article_view_args.update({'month': str(obj.date.month).zfill(2)})
265                                                 if self.article_permalink_style == 'D':
266                                                         article_view_args.update({'day': str(obj.date.day).zfill(2)})
267                                 return reverse(self.article_view, urlconf=self, kwargs=article_view_args)
268                 elif isinstance(obj, NewsletterIssue):
269                         if obj.newsletter == self.newsletter:
270                                 return reverse(self.issue_view, urlconf=self, kwargs={'number': str(obj.number)})
271                 raise ViewCanNotProvideSubpath
272         
273         @property
274         def urlpatterns(self):
275                 base_patterns = patterns('',
276                         url(r'^$', self.index_view),
277                         url((r'^(?:%s)/?$' % self.issue_permalink_base), self.issue_archive_view),
278                         url((r'^(?:%s)/(?P<number>\d+)/?$' % self.issue_permalink_base), self.issue_view)
279                 )
280                 article_patterns = patterns('',
281                         url((r'^(?:%s)/?$' % self.article_permalink_base), self.article_archive_view)
282                 )
283                 if self.article_permalink_style in 'DMY':
284                         article_patterns += patterns('',
285                                 url((r'^(?:%s)/(?P<year>\d{4})/?$' % self.article_permalink_base), self.article_archive_view)
286                         )
287                         if self.article_permalink_style in 'DM':
288                                 article_patterns += patterns('',
289                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/?$' % self.article_permalink_base), self.article_archive_view)
290                                 )
291                                 if self.article_permalink_style == 'D':
292                                         article_patterns += patterns('',
293                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/?$' % self.article_permalink_base), self.article_archive_view),
294                                                 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)
295                                         )
296                                 else:
297                                         article_patterns += patterns('',
298                                                 url((r'^(?:%s)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
299                                         )
300                         else:
301                                 article_patterns += patterns('',
302                                         url((r'^(?:%s)/(?P<year>\d{4})/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
303                                 )
304                 else:
305                         article_patterns += patterns('',
306                                 url((r'^(?:%s)/(?P<slug>[-\w]+)/?$' % self.article_permalink_base), self.article_view)
307                         )
308                 return base_patterns + article_patterns
309         
310         def index_view(self, request, node=None, extra_context=None):
311                 context = {}
312                 context.update(extra_context or {})
313                 context.update({'newsletter': self.newsletter})
314                 return self.index_page.render_to_response(node, request, extra_context=context)
315         
316         def article_view(self, request, slug, year=None, month=None, day=None, node=None, extra_context=None):
317                 articles = self.newsletter.articles.all()
318                 if year:
319                         articles = articles.filter(date__year=year)
320                 if month:
321                         articles = articles.filter(date__month=month)
322                 if day:
323                         articles = articles.filter(date__day=day)
324                 try:
325                         article = articles.get(slug=slug)
326                 except:
327                         raise Http404
328                 context = {}
329                 context.update(extra_context or {})
330                 context.update({'newsletter': self.newsletter, 'article': article})
331                 return self.article_page.render_to_response(node, request, extra_context=context)
332         
333         def article_archive_view(self, request, year=None, month=None, day=None, node=None, extra_context=None):
334                 if not self.article_archive_page:
335                         raise Http404
336                 articles = self.newsletter.articles.all()
337                 if year:
338                         articles = articles.filter(date__year=year)
339                 if month:
340                         articles = articles.filter(date__month=month)
341                 if day:
342                         articles = articles.filter(date__day=day)
343                 context = {}
344                 context.update(extra_context or {})
345                 context.update({'newsletter': self.newsletter, 'year': year, 'month': month, 'day': day, 'articles': articles})
346                 return self.article_archive_page.render_to_response(node, request, extra_context=context)
347         
348         def issue_view(self, request, number, node=None, extra_context=None):
349                 try:
350                         issue = self.newsletter.issues.get(number=number)
351                 except:
352                         raise Http404
353                 context = {}
354                 context.update(extra_context or {})
355                 context.update({'newsletter': self.newsletter, 'issue': issue})
356                 return self.issue_page.render_to_response(node, request, extra_context=context)
357         
358         def issue_archive_view(self, request, node=None, extra_context=None):
359                 if not self.issue_archive_page:
360                         raise Http404
361                 context = {}
362                 context.update(extra_context or {})
363                 context.update({'newsletter': self.newsletter})
364                 return self.issue_archive_page.render_to_response(node, request, extra_context=context)