Merge remote-tracking branch 'ithinksw/develop' into develop
[philo.git] / philo / contrib / penfield / models.py
1 # encoding: utf-8
2 from datetime import date, datetime
3
4 from django.conf import settings
5 from django.conf.urls.defaults import url, patterns, include
6 from django.db import models
7 from django.http import Http404, HttpResponse
8
9 from philo.contrib.winer.models import FeedView
10 from philo.exceptions import ViewCanNotProvideSubpath
11 from philo.models import Tag, Entity, Page, register_value_model
12 from philo.models.fields import TemplateField
13 from philo.utils import paginate
14
15
16 class Blog(Entity):
17         """Represents a blog which can be posted to."""
18         #: The name of the :class:`Blog`, currently called 'title' for historical reasons.
19         title = models.CharField(max_length=255)
20         
21         #: A slug used to identify the :class:`Blog`.
22         slug = models.SlugField(max_length=255)
23         
24         def __unicode__(self):
25                 return self.title
26         
27         @property
28         def entry_tags(self):
29                 """Returns a :class:`QuerySet` of :class:`.Tag`\ s that are used on any entries in this blog."""
30                 return Tag.objects.filter(blogentries__blog=self).distinct()
31         
32         @property
33         def entry_dates(self):
34                 """Returns a dictionary of date :class:`QuerySet`\ s for years, months, and days for which there are entries."""
35                 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')}
36                 return dates
37
38
39 register_value_model(Blog)
40
41
42 class BlogEntry(Entity):
43         """Represents an entry in a :class:`Blog`."""
44         #: The title of the :class:`BlogEntry`.
45         title = models.CharField(max_length=255)
46         
47         #: A slug which identifies the :class:`BlogEntry`.
48         slug = models.SlugField(max_length=255)
49         
50         #: The :class:`Blog` which this entry has been posted to. Can be left blank to represent a "draft" status.
51         blog = models.ForeignKey(Blog, related_name='entries', blank=True, null=True)
52         
53         #: A :class:`ForeignKey` to the author. The model is either :setting:`PHILO_PERSON_MODULE` or :class:`auth.User`.
54         author = models.ForeignKey(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='blogentries')
55         
56         #: The date and time which the :class:`BlogEntry` is considered posted at.
57         date = models.DateTimeField(default=None)
58         
59         #: The content of the :class:`BlogEntry`.
60         content = models.TextField()
61         
62         #: An optional brief excerpt from the :class:`BlogEntry`.
63         excerpt = models.TextField(blank=True, null=True)
64         
65         #: :class:`.Tag`\ s for this :class:`BlogEntry`.
66         tags = models.ManyToManyField(Tag, related_name='blogentries', blank=True, null=True)
67         
68         def save(self, *args, **kwargs):
69                 if self.date is None:
70                         self.date = datetime.now()
71                 super(BlogEntry, self).save(*args, **kwargs)
72         
73         def __unicode__(self):
74                 return self.title
75         
76         class Meta:
77                 ordering = ['-date']
78                 verbose_name_plural = "blog entries"
79                 get_latest_by = "date"
80
81
82 register_value_model(BlogEntry)
83
84
85 class BlogView(FeedView):
86         """
87         A subclass of :class:`.FeedView` which handles patterns and feeds for a :class:`Blog` and its related :class:`entries <BlogEntry>`.
88         
89         """
90         ENTRY_PERMALINK_STYLE_CHOICES = (
91                 ('D', 'Year, month, and day'),
92                 ('M', 'Year and month'),
93                 ('Y', 'Year'),
94                 ('B', 'Custom base'),
95                 ('N', 'No base')
96         )
97         
98         #: The :class:`Blog` whose entries should be managed by this :class:`BlogView`
99         blog = models.ForeignKey(Blog, related_name='blogviews')
100         
101         #: The main page of the :class:`Blog` will be rendered with this :class:`.Page`.
102         index_page = models.ForeignKey(Page, related_name='blog_index_related')
103         #: The detail view of a :class:`BlogEntry` will be rendered with this :class:`Page`.
104         entry_page = models.ForeignKey(Page, related_name='blog_entry_related')
105         # TODO: entry_archive is misleading. Rename to ymd_page or timespan_page.
106         #: Views of :class:`BlogEntry` archives will be rendered with this :class:`Page` (optional).
107         entry_archive_page = models.ForeignKey(Page, related_name='blog_entry_archive_related', null=True, blank=True)
108         #: Views of :class:`BlogEntry` archives according to their :class:`.Tag`\ s will be rendered with this :class:`Page`.
109         tag_page = models.ForeignKey(Page, related_name='blog_tag_related')
110         #: The archive of all available tags will be rendered with this :class:`Page` (optional).
111         tag_archive_page = models.ForeignKey(Page, related_name='blog_tag_archive_related', null=True, blank=True)
112         #: This number will be passed directly into pagination for :class:`BlogEntry` list pages. Pagination will be disabled if this is left blank.
113         entries_per_page = models.IntegerField(blank=True, null=True)
114         
115         #: Depending on the needs of the site, different permalink styles may be appropriate. Example subpaths are provided for a :class:`BlogEntry` posted on May 2nd, 2011 with a slug of "hello". The choices are:
116         #: 
117         #:      * Year, month, and day - ``2011/05/02/hello``
118         #:      * Year and month - ``2011/05/hello``
119         #:      * Year - ``2011/hello``
120         #:      * Custom base - :attr:`entry_permalink_base`\ ``/hello``
121         #:      * No base - ``hello``
122         entry_permalink_style = models.CharField(max_length=1, choices=ENTRY_PERMALINK_STYLE_CHOICES)
123         #: If the :attr:`entry_permalink_style` is set to "Custom base" then the value of this field will be used as the base subpath for year/month/day entry archive pages and entry detail pages. Default: "entries"
124         entry_permalink_base = models.CharField(max_length=255, blank=False, default='entries')
125         #: This will be used as the base for the views of :attr:`tag_page` and :attr:`tag_archive_page`. Default: "tags"
126         tag_permalink_base = models.CharField(max_length=255, blank=False, default='tags')
127         
128         item_context_var = 'entries'
129         
130         def __unicode__(self):
131                 return u'BlogView for %s' % self.blog.title
132         
133         def get_reverse_params(self, obj):
134                 if isinstance(obj, BlogEntry):
135                         if obj.blog_id == self.blog_id:
136                                 kwargs = {'slug': obj.slug}
137                                 if self.entry_permalink_style in 'DMY':
138                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
139                                         if self.entry_permalink_style in 'DM':
140                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
141                                                 if self.entry_permalink_style == 'D':
142                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
143                                 return self.entry_view, [], kwargs
144                 elif isinstance(obj, Tag) or (isinstance(obj, models.query.QuerySet) and obj.model == Tag and obj):
145                         if isinstance(obj, Tag):
146                                 obj = [obj]
147                         slugs = [tag.slug for tag in obj if tag in self.get_tag_queryset(self.blog)]
148                         if slugs:
149                                 return 'entries_by_tag', [], {'tag_slugs': "/".join(slugs)}
150                 elif isinstance(obj, (date, datetime)):
151                         kwargs = {
152                                 'year': str(obj.year).zfill(4),
153                                 'month': str(obj.month).zfill(2),
154                                 'day': str(obj.day).zfill(2)
155                         }
156                         return 'entries_by_day', [], kwargs
157                 raise ViewCanNotProvideSubpath
158         
159         @property
160         def urlpatterns(self):
161                 urlpatterns = self.feed_patterns(r'^', 'get_entries', 'index_page', 'index') +\
162                         self.feed_patterns(r'^%s/(?P<tag_slugs>[-\w]+[-+/\w]*)' % self.tag_permalink_base, 'get_entries', 'tag_page', 'entries_by_tag')
163                 
164                 if self.tag_archive_page_id:
165                         urlpatterns += patterns('',
166                                 url((r'^%s$' % self.tag_permalink_base), self.tag_archive_view, name='tag_archive')
167                         )
168                 
169                 if self.entry_archive_page_id:
170                         if self.entry_permalink_style in 'DMY':
171                                 urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})', 'get_entries', 'entry_archive_page', 'entries_by_year')
172                                 if self.entry_permalink_style in 'DM':
173                                         urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})/(?P<month>\d{2})', 'get_entries', 'entry_archive_page', 'entries_by_month')
174                                         if self.entry_permalink_style == 'D':
175                                                 urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', 'get_entries', 'entry_archive_page', 'entries_by_day')
176                 
177                 if self.entry_permalink_style == 'D':
178                         urlpatterns += patterns('',
179                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)$', self.entry_view)
180                         )
181                 elif self.entry_permalink_style == 'M':
182                         urlpatterns += patterns('',
183                                 url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)$', self.entry_view)
184                         )
185                 elif self.entry_permalink_style == 'Y':
186                         urlpatterns += patterns('',
187                                 url(r'^(?P<year>\d{4})/(?P<slug>[-\w]+)$', self.entry_view)
188                         )
189                 elif self.entry_permalink_style == 'B':
190                         urlpatterns += patterns('',
191                                 url((r'^%s/(?P<slug>[-\w]+)$' % self.entry_permalink_base), self.entry_view)
192                         )
193                 else:
194                         urlpatterns += patterns('',
195                                 url(r'^(?P<slug>[-\w]+)$', self.entry_view)
196                         )
197                 return urlpatterns
198         
199         def get_entry_queryset(self, obj):
200                 """Returns the default :class:`QuerySet` of :class:`BlogEntry` instances for the :class:`BlogView` - all entries that are considered posted in the past. This allows for scheduled posting of entries."""
201                 return obj.entries.filter(date__lte=datetime.now())
202         
203         def get_tag_queryset(self, obj):
204                 """Returns the default :class:`QuerySet` of :class:`.Tag`\ s for the :class:`BlogView`'s :meth:`get_entries_by_tag` and :meth:`tag_archive_view`."""
205                 return obj.entry_tags
206         
207         def get_object(self, request, year=None, month=None, day=None, tag_slugs=None):
208                 """Returns a dictionary representing the parameters for a feed which will be exposed."""
209                 if tag_slugs is None:
210                         tags = None
211                 else:
212                         tag_slugs = tag_slugs.replace('+', '/').split('/')
213                         tags = self.get_tag_queryset(self.blog).filter(slug__in=tag_slugs)
214                         if not tags:
215                                 raise Http404
216                         
217                         # Raise a 404 on an incorrect slug.
218                         found_slugs = set([tag.slug for tag in tags])
219                         for slug in tag_slugs:
220                                 if slug and slug not in found_slugs:
221                                         raise Http404
222                 
223                 try:
224                         if year and month and day:
225                                 context_date = date(int(year), int(month), int(day))
226                         elif year and month:
227                                 context_date = date(int(year), int(month), 1)
228                         elif year:
229                                 context_date = date(int(year), 1, 1)
230                         else:
231                                 context_date = None
232                 except TypeError, ValueError:
233                         context_date = None
234                 
235                 return {
236                         'blog': self.blog,
237                         'tags': tags,
238                         'year': year,
239                         'month': month,
240                         'day': day,
241                         'date': context_date
242                 }
243         
244         def get_entries(self, obj, request, year=None, month=None, day=None, tag_slugs=None, extra_context=None):
245                 """Returns the :class:`BlogEntry` objects which will be exposed for the given object, as returned from :meth:`get_object`."""
246                 entries = self.get_entry_queryset(obj['blog'])
247                 
248                 if obj['tags'] is not None:
249                         tags = obj['tags']
250                         for tag in tags:
251                                 entries = entries.filter(tags=tag)
252                 
253                 if obj['date'] is not None:
254                         if year:
255                                 entries = entries.filter(date__year=year)
256                         if month:
257                                 entries = entries.filter(date__month=month)
258                         if day:
259                                 entries = entries.filter(date__day=day)
260                 
261                 context = extra_context or {}
262                 context.update(obj)
263                 
264                 return entries, context
265         
266         def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
267                 """Renders :attr:`entry_page` with the entry specified by the given parameters."""
268                 entries = self.get_entry_queryset(self.blog)
269                 if year:
270                         entries = entries.filter(date__year=year)
271                 if month:
272                         entries = entries.filter(date__month=month)
273                 if day:
274                         entries = entries.filter(date__day=day)
275                 try:
276                         entry = entries.get(slug=slug)
277                 except:
278                         raise Http404
279                 context = self.get_context()
280                 context.update(extra_context or {})
281                 context.update({'entry': entry})
282                 return self.entry_page.render_to_response(request, extra_context=context)
283         
284         def tag_archive_view(self, request, extra_context=None):
285                 """Renders :attr:`tag_archive_page` with the result of :meth:`get_tag_queryset` added to the context."""
286                 if not self.tag_archive_page:
287                         raise Http404
288                 context = self.get_context()
289                 context.update(extra_context or {})
290                 context.update({
291                         'tags': self.get_tag_queryset(self.blog)
292                 })
293                 return self.tag_archive_page.render_to_response(request, extra_context=context)
294         
295         def process_page_items(self, request, items):
296                 """Overrides :meth:`.FeedView.process_page_items` to add pagination."""
297                 if self.entries_per_page:
298                         page_num = request.GET.get('page', 1)
299                         paginator, paginated_page, items = paginate(items, self.entries_per_page, page_num)
300                         item_context = {
301                                 'paginator': paginator,
302                                 'paginated_page': paginated_page,
303                                 self.item_context_var: items
304                         }
305                 else:
306                         item_context = {
307                                 self.item_context_var: items
308                         }
309                 return items, item_context
310         
311         def title(self, obj):
312                 title = obj['blog'].title
313                 if obj['tags']:
314                         title += u" â€“ %s" % u", ".join((tag.name for tag in obj['tags']))
315                 date = obj['date']
316                 if date:
317                         if obj['day']:
318                                 datestr = date.strftime("%F %j, %Y")
319                         elif obj['month']:
320                                 datestr = date.strftime("%F, %Y")
321                         elif obj['year']:
322                                 datestr = date.strftime("%Y")
323                         title += u" â€“ %s" % datestr
324                 return title
325         
326         def categories(self, obj):
327                 tags = obj['tags']
328                 if tags:
329                         return (tag.name for tag in tags)
330                 return None
331         
332         def item_title(self, item):
333                 return item.title
334         
335         def item_description(self, item):
336                 return item.content
337         
338         def item_author_name(self, item):
339                 return item.author.get_full_name()
340         
341         def item_pubdate(self, item):
342                 return item.date
343         
344         def item_categories(self, item):
345                 return [tag.name for tag in item.tags.all()]
346
347
348 class Newsletter(Entity):
349         """Represents a newsletter which will contain :class:`articles <NewsletterArticle>` organized into :class:`issues <NewsletterIssue>`."""
350         #: The name of the :class:`Newsletter`, currently callse 'title' for historical reasons.
351         title = models.CharField(max_length=255)
352         #: A slug used to identify the :class:`Newsletter`.
353         slug = models.SlugField(max_length=255)
354         
355         def __unicode__(self):
356                 return self.title
357
358
359 register_value_model(Newsletter)
360
361
362 class NewsletterArticle(Entity):
363         """Represents an article in a :class:`Newsletter`"""
364         #: The title of the :class:`NewsletterArticle`.
365         title = models.CharField(max_length=255)
366         #: A slug which identifies the :class:`NewsletterArticle`.
367         slug = models.SlugField(max_length=255)
368         #: A :class:`ForeignKey` to :class:`Newsletter` representing the newsletter which this article was written for.
369         newsletter = models.ForeignKey(Newsletter, related_name='articles')
370         #: A :class:`ManyToManyField` to the author(s) of the :class:`NewsletterArticle`. The model is either :setting:`PHILO_PERSON_MODULE` or :class:`auth.User`.
371         authors = models.ManyToManyField(getattr(settings, 'PHILO_PERSON_MODULE', 'auth.User'), related_name='newsletterarticles')
372         #: The date and time which the :class:`NewsletterArticle` is considered published at.
373         date = models.DateTimeField(default=None)
374         #: A :class:`.TemplateField` containing an optional short summary of the article, meant to grab a reader's attention and draw them in.
375         lede = TemplateField(null=True, blank=True, verbose_name='Summary')
376         #: A :class:`.TemplateField` containing the full text of the article.
377         full_text = TemplateField(db_index=True)
378         #: A :class:`ManyToManyField` to :class:`.Tag`\ s for the :class:`NewsletterArticle`.
379         tags = models.ManyToManyField(Tag, related_name='newsletterarticles', blank=True, null=True)
380         
381         def save(self, *args, **kwargs):
382                 if self.date is None:
383                         self.date = datetime.now()
384                 super(NewsletterArticle, self).save(*args, **kwargs)
385         
386         def __unicode__(self):
387                 return self.title
388         
389         class Meta:
390                 get_latest_by = 'date'
391                 ordering = ['-date']
392                 unique_together = (('newsletter', 'slug'),)
393
394
395 register_value_model(NewsletterArticle)
396
397
398 class NewsletterIssue(Entity):
399         """Represents an issue of the newsletter."""
400         #: The title of the :class:`NewsletterIssue`.
401         title = models.CharField(max_length=255)
402         #: A slug which identifies the :class:`NewsletterIssue`.
403         slug = models.SlugField(max_length=255)
404         #: A :class:`ForeignKey` to the :class:`Newsletter` which this issue belongs to.
405         newsletter = models.ForeignKey(Newsletter, related_name='issues')
406         #: The numbering of the issue - for example, 04.02 for volume 4, issue 2. This is an instance of :class:`CharField` to allow any arbitrary numbering system.
407         numbering = models.CharField(max_length=50, help_text='For example, 04.02 for volume 4, issue 2.')
408         #: A :class:`ManyToManyField` to articles belonging to this issue.
409         articles = models.ManyToManyField(NewsletterArticle, related_name='issues')
410         
411         def __unicode__(self):
412                 return self.title
413         
414         class Meta:
415                 ordering = ['-numbering']
416                 unique_together = (('newsletter', 'numbering'),)
417
418
419 register_value_model(NewsletterIssue)
420
421
422 class NewsletterView(FeedView):
423         """A subclass of :class:`.FeedView` which handles patterns and feeds for a :class:`Newsletter` and its related :class:`articles <NewsletterArticle>`."""
424         ARTICLE_PERMALINK_STYLE_CHOICES = (
425                 ('D', 'Year, month, and day'),
426                 ('M', 'Year and month'),
427                 ('Y', 'Year'),
428                 ('S', 'Slug only')
429         )
430         
431         #: A :class:`ForeignKey` to the :class:`Newsletter` managed by this :class:`NewsletterView`.
432         newsletter = models.ForeignKey(Newsletter, related_name='newsletterviews')
433         
434         #: A :class:`ForeignKey` to the :class:`Page` used to render the main page of this :class:`NewsletterView`.
435         index_page = models.ForeignKey(Page, related_name='newsletter_index_related')
436         #: A :class:`ForeignKey` to the :class:`Page` used to render the detail view of a :class:`NewsletterArticle` for this :class:`NewsletterView`.
437         article_page = models.ForeignKey(Page, related_name='newsletter_article_related')
438         #: A :class:`ForeignKey` to the :class:`Page` used to render the :class:`NewsletterArticle` archive pages for this :class:`NewsletterView`.
439         article_archive_page = models.ForeignKey(Page, related_name='newsletter_article_archive_related', null=True, blank=True)
440         #: A :class:`ForeignKey` to the :class:`Page` used to render the detail view of a :class:`NewsletterIssue` for this :class:`NewsletterView`.
441         issue_page = models.ForeignKey(Page, related_name='newsletter_issue_related')
442         #: A :class:`ForeignKey` to the :class:`Page` used to render the :class:`NewsletterIssue` archive pages for this :class:`NewsletterView`.
443         issue_archive_page = models.ForeignKey(Page, related_name='newsletter_issue_archive_related', null=True, blank=True)
444         
445         #: Depending on the needs of the site, different permalink styles may be appropriate. Example subpaths are provided for a :class:`NewsletterArticle` posted on May 2nd, 2011 with a slug of "hello". The choices are:
446         #: 
447         #:      * Year, month, and day - :attr:`article_permalink_base`\ ``/2011/05/02/hello``
448         #:      * Year and month - :attr:`article_permalink_base`\ ``/2011/05/hello``
449         #:      * Year - :attr:`article_permalink_base`\ ``/2011/hello``
450         #:      * Slug only - :attr:`article_permalink_base`\ ``/hello``
451         article_permalink_style = models.CharField(max_length=1, choices=ARTICLE_PERMALINK_STYLE_CHOICES)
452         #: This will be used as the base subpath for year/month/day article archive pages and article detail pages. Default: "articles"
453         article_permalink_base = models.CharField(max_length=255, blank=False, default='articles')
454         #: This will be used as the base subpath for issue detail pages and the issue archive page.
455         issue_permalink_base = models.CharField(max_length=255, blank=False, default='issues')
456         
457         item_context_var = 'articles'
458         object_attr = 'newsletter'
459         
460         def __unicode__(self):
461                 return "NewsletterView for %s" % self.newsletter.__unicode__()
462         
463         def get_reverse_params(self, obj):
464                 if isinstance(obj, NewsletterArticle):
465                         if obj.newsletter_id == self.newsletter_id:
466                                 kwargs = {'slug': obj.slug}
467                                 if self.article_permalink_style in 'DMY':
468                                         kwargs.update({'year': str(obj.date.year).zfill(4)})
469                                         if self.article_permalink_style in 'DM':
470                                                 kwargs.update({'month': str(obj.date.month).zfill(2)})
471                                                 if self.article_permalink_style == 'D':
472                                                         kwargs.update({'day': str(obj.date.day).zfill(2)})
473                                 return self.article_view, [], kwargs
474                 elif isinstance(obj, NewsletterIssue):
475                         if obj.newsletter_id == self.newsletter_id:
476                                 return 'issue', [], {'numbering': obj.numbering}
477                 elif isinstance(obj, (date, datetime)):
478                         kwargs = {
479                                 'year': str(obj.year).zfill(4),
480                                 'month': str(obj.month).zfill(2),
481                                 'day': str(obj.day).zfill(2)
482                         }
483                         return 'articles_by_day', [], kwargs
484                 raise ViewCanNotProvideSubpath
485         
486         @property
487         def urlpatterns(self):
488                 urlpatterns = self.feed_patterns(r'^', 'get_all_articles', 'index_page', 'index') + patterns('',
489                         url(r'^%s/(?P<numbering>.+)$' % self.issue_permalink_base, self.page_view('get_articles_by_issue', 'issue_page'), name='issue')
490                 )
491                 if self.issue_archive_page_id:
492                         urlpatterns += patterns('',
493                                 url(r'^%s$' % self.issue_permalink_base, self.issue_archive_view, 'issue_archive')
494                         )
495                 if self.article_archive_page_id:
496                         urlpatterns += self.feed_patterns(r'^%s' % self.article_permalink_base, 'get_all_articles', 'article_archive_page', 'articles')
497                         if self.article_permalink_style in 'DMY':
498                                 urlpatterns += self.feed_patterns(r'^%s/(?P<year>\d{4})' % self.article_permalink_base, 'get_articles_by_ymd', 'article_archive_page', 'articles_by_year')
499                                 if self.article_permalink_style in 'DM':
500                                         urlpatterns += self.feed_patterns(r'^%s/(?P<year>\d{4})/(?P<month>\d{2})' % self.article_permalink_base, 'get_articles_by_ymd', 'article_archive_page', 'articles_by_month')
501                                         if self.article_permalink_style == 'D':
502                                                 urlpatterns += self.feed_patterns(r'^%s/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})' % self.article_permalink_base, 'get_articles_by_ymd', 'article_archive_page', 'articles_by_day')
503                 
504                 if self.article_permalink_style == 'Y':
505                         urlpatterns += patterns('',
506                                 url(r'^%s/(?P<year>\d{4})/(?P<slug>[\w-]+)$' % self.article_permalink_base, self.article_view)
507                         )
508                 elif self.article_permalink_style == 'M':
509                         urlpatterns += patterns('',
510                                 url(r'^%s/(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[\w-]+)$' % self.article_permalink_base, self.article_view)
511                         )
512                 elif self.article_permalink_style == 'D':
513                         urlpatterns += patterns('',
514                                 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)
515                         )
516                 else:   
517                         urlpatterns += patterns('',
518                                 url(r'^%s/(?P<slug>[-\w]+)$' % self.article_permalink_base, self.article_view)
519                         )
520                 
521                 return urlpatterns
522         
523         def get_context(self):
524                 return {'newsletter': self.newsletter}
525         
526         def get_article_queryset(self, obj):
527                 """Returns the default :class:`QuerySet` of :class:`NewsletterArticle` instances for the :class:`NewsletterView` - all articles that are considered posted in the past. This allows for scheduled posting of articles."""
528                 return obj.articles.filter(date__lte=datetime.now())
529         
530         def get_issue_queryset(self, obj):
531                 """Returns the default :class:`QuerySet` of :class:`NewsletterIssue` instances for the :class:`NewsletterView`."""
532                 return obj.issues.all()
533         
534         def get_all_articles(self, obj, request, extra_context=None):
535                 """Used to generate :meth:`~.FeedView.feed_patterns` for all entries."""
536                 return self.get_article_queryset(obj), extra_context
537         
538         def get_articles_by_ymd(self, obj, request, year, month=None, day=None, extra_context=None):
539                 """Used to generate :meth:`~.FeedView.feed_patterns` for a specific year, month, and day."""
540                 articles = self.get_article_queryset(obj).filter(date__year=year)
541                 if month:
542                         articles = articles.filter(date__month=month)
543                 if day:
544                         articles = articles.filter(date__day=day)
545                 return articles, extra_context
546         
547         def get_articles_by_issue(self, obj, request, numbering, extra_context=None):
548                 """Used to generate :meth:`~.FeedView.feed_patterns` for articles from a certain issue."""
549                 try:
550                         issue = self.get_issue_queryset(obj).get(numbering=numbering)
551                 except NewsletterIssue.DoesNotExist:
552                         raise Http404
553                 context = extra_context or {}
554                 context.update({'issue': issue})
555                 return self.get_article_queryset(obj).filter(issues=issue), context
556         
557         def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
558                 """Renders :attr:`article_page` with the article specified by the given parameters."""
559                 articles = self.get_article_queryset(self.newsletter)
560                 if year:
561                         articles = articles.filter(date__year=year)
562                 if month:
563                         articles = articles.filter(date__month=month)
564                 if day:
565                         articles = articles.filter(date__day=day)
566                 try:
567                         article = articles.get(slug=slug)
568                 except NewsletterArticle.DoesNotExist:
569                         raise Http404
570                 context = self.get_context()
571                 context.update(extra_context or {})
572                 context.update({'article': article})
573                 return self.article_page.render_to_response(request, extra_context=context)
574         
575         def issue_archive_view(self, request, extra_context):
576                 """Renders :attr:`issue_archive_page` with the result of :meth:`get_issue_queryset` added to the context."""
577                 if not self.issue_archive_page:
578                         raise Http404
579                 context = self.get_context()
580                 context.update(extra_context or {})
581                 context.update({
582                         'issues': self.get_issue_queryset(self.newsletter)
583                 })
584                 return self.issue_archive_page.render_to_response(request, extra_context=context)
585         
586         def title(self, obj):
587                 return obj.title
588         
589         def item_title(self, item):
590                 return item.title
591         
592         def item_description(self, item):
593                 return item.full_text
594         
595         def item_author_name(self, item):
596                 authors = list(item.authors.all())
597                 if len(authors) > 1:
598                         return "%s and %s" % (", ".join([author.get_full_name() for author in authors[:-1]]), authors[-1].get_full_name())
599                 elif authors:
600                         return authors[0].get_full_name()
601                 else:
602                         return ''
603         
604         def item_pubdate(self, item):
605                 return item.date
606         
607         def item_categories(self, item):
608                 return [tag.name for tag in item.tags.all()]