Question

I was able to preview the 100 most recent items in my news clipping database on my website's index page with a generic view:

DPRM

Now I need to paginate my database in a separate logical section of my website. I need to paginate by year. I don't care how many entries are in each year, I just want to take the year from the URL, fetch the database items from that year (i.e. /newsitems/validyearhere), and present it to the user with a way to navigate through years. There is a way to do this in Rails but I couldn't find a way in Django.

Will I be able to use the currently deployed model?

from django.db import models

class Article(models.Model):
    headline = models.CharField(max_length=100)
    subhead = models.CharField(max_length=50)
    publication = models.CharField(max_length=30)
    author = models.CharField(max_length=50)
    date = models.DateField()
    website = models.URLField()

    def __unicode__(self):
        return self.headline

Will I have to add a redundant Year database field, in addition to the current date field? Will the schema need to evolve in any way to accommodate this?

I also need it to fail gracefully if the user puts in a year with no entries or data that is not a year.

Please explain this as simply as you can as I am very new to Django and am finding the learning curve steep.

Était-ce utile?

La solution

With the new Class Based Views the easies would be to use the YearArchiveView

class ArticleYearArchiveView(YearArchiveView):
    model = Article
    paginate_by = 100
    context_object_name = 'article_list'
    date_field = 'date'
    allow_empty = True

Allow empty is to show the page even when there's no elements for that year

in your urls.py you would need something like

url(r'^newsitems/(?P<year>\d+)/$', ArticleYearArchiveView.as_view()),

Autres conseils

Yes your model is fine.. Why not write a class based view?

class SomeListView(ListView):
    model = Article
    paginate_by = 100
    template_name = "app/template.html"
    context_object_name = "articles" # or use object_list

    def get_queryset(self):
        return Article.objects.order_by('-date')

You can add a different filter in get_queryset to create a list with results by year, and in your template you can iterate over them and create custom buttons (with year info)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top