# Path: django_fortunes/models.py
# class Fortune(models.Model):
#     author = models.ForeignKey(User)
#     title = models.CharField(max_length=200, blank=False)
#     slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date')
#     content = models.TextField(blank=False)
#     pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now())
#     votes = models.IntegerField(default=0)
#     comments = generic.GenericRelation(
#         Comment,
#         content_type_field='content_type',
#         object_id_field='object_pk'
#     )
# 
#     objects = FortuneManager()
# 
#     def __unicode__(self):
#         return _("%(title)s, from %(author)s") % {
#             'title': self.title,
#             'author': self.author.username ,
#         }
# 
#     def check_slug(self):
#         """
#         If no slug has been generated yet for the current Fortune, tries to generate a
#         unique one
#         """
#         if not self.slug:
#             prefix = ""
#             i = 0
#             while True:
#                 self.slug = prefix + slugify(self.title)
#                 try:
#                     self._default_manager.values('id').get(slug=self.slug)
#                     i += 1
#                     prefix = str(i) + "-"
#                 except Fortune.DoesNotExist:
#                     break
#         return self.slug
# 
#     @models.permalink
#     def get_absolute_url(self):
#         "Retrieves the absolute django url of a fortune"
#         return ('fortune_detail', (), {
#             'slug': self.slug,
#             'year': self.pub_date.year,
#             'month': self.pub_date.month,
#             'day': self.pub_date.day
#         })
# 
#     def save(self):
#         "Saves a fortune after havng checked and generated its slug"
#         self.check_slug()
#         super(Fortune, self).save()
# 
# Path: django_fortunes/forms.py
# class PublicFortuneForm(FortuneForm):
#     class Meta(FortuneForm.Meta):
#         exclude = ('author', 'pub_date', 'votes', 'slug',)


from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.conf import settings
from django.views.generic import date_based, list_detail
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django_fortunes.models import Fortune
from django_fortunes.forms import PublicFortuneForm
      paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3),
      template_name = template_name,
      template_object_name = template_object_name,
      extra_context = extra,
      **kwargs
    )

@login_required
def fortune_new(request, template_name='new.html'):
    '''
    Provides a Fortune creation form, validates the form if values posted 
    and saves a new Fortune in the database if everything's okay
    '''
    if request.method == 'POST':
        form = PublicFortuneForm(request.POST)
        if form.is_valid():
            fortune = form.save(commit=False)
            fortune.author = request.user
            fortune.save()
            return redirect(fortune)
    else:
        form = PublicFortuneForm()
    return render_to_response(template_name,
                              {'form': form, 'section': 'new'},
                              context_instance=RequestContext(request))

def fortune_vote(request, object_pk, direction):
    '''
    Votes up or down a fortune
    '''

# Path: django_fortunes/models.py
# class Fortune(models.Model):
#     author = models.ForeignKey(User)
#     title = models.CharField(max_length=200, blank=False)
#     slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date')
#     content = models.TextField(blank=False)
#     pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now())
#     votes = models.IntegerField(default=0)
#     comments = generic.GenericRelation(
#         Comment,
#         content_type_field='content_type',
#         object_id_field='object_pk'
#     )
# 
#     objects = FortuneManager()
# 
#     def __unicode__(self):
#         return _("%(title)s, from %(author)s") % {
#             'title': self.title,
#             'author': self.author.username ,
#         }
# 
#     def check_slug(self):
#         """
#         If no slug has been generated yet for the current Fortune, tries to generate a
#         unique one
#         """
#         if not self.slug:
#             prefix = ""
#             i = 0
#             while True:
#                 self.slug = prefix + slugify(self.title)
#                 try:
#                     self._default_manager.values('id').get(slug=self.slug)
#                     i += 1
#                     prefix = str(i) + "-"
#                 except Fortune.DoesNotExist:
#                     break
#         return self.slug
# 
#     @models.permalink
#     def get_absolute_url(self):
#         "Retrieves the absolute django url of a fortune"
#         return ('fortune_detail', (), {
#             'slug': self.slug,
#             'year': self.pub_date.year,
#             'month': self.pub_date.month,
#             'day': self.pub_date.day
#         })
# 
#     def save(self):
#         "Saves a fortune after havng checked and generated its slug"
#         self.check_slug()
#         super(Fortune, self).save()
# 
# Path: django_fortunes/forms.py
# class PublicFortuneForm(FortuneForm):
#     class Meta(FortuneForm.Meta):
#         exclude = ('author', 'pub_date', 'votes', 'slug',)


# Path: django_fortunes/views.py
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.conf import settings
from django.views.generic import date_based, list_detail
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django_fortunes.models import Fortune
from django_fortunes.forms import PublicFortuneForm

      paginate_by = getattr(settings, 'FORTUNES_MAX_PER_PAGE', 3),
      template_name = template_name,
      template_object_name = template_object_name,
      extra_context = extra,
      **kwargs
    )

@login_required
def fortune_new(request, template_name='new.html'):
    '''
    Provides a Fortune creation form, validates the form if values posted 
    and saves a new Fortune in the database if everything's okay
    '''
    if request.method == 'POST':
        form = PublicFortuneForm(request.POST)
        if form.is_valid():
            fortune = form.save(commit=False)
            fortune.author = request.user
            fortune.save()
            return redirect(fortune)
    else:
        form = PublicFortuneForm()
    return render_to_response(template_name,
                              {'form': form, 'section': 'new'},
                              context_instance=RequestContext(request))

def fortune_vote(request, object_pk, direction):
    '''
    Votes up or down a fortune
    '''

    fortune = get_object_or_404(Fortune, pk=object_pk)