Django有问题的观点

时间:2011-08-11 09:53:59

标签: python django django-templates django-views django-generic-views

我有这个Django通用视图:

def post_list(request, page=0, paginate_by=1, **kwargs):
page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by)
return list_detail.object_list(
    request,
    queryset=Post.objects.published(),
    paginate_by=page_size,
    page=page,
    **kwargs
)
post_list.__doc__ = list_detail.object_list.__doc__

我希望将当前年份发送给模板使用它。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

通过当前年份的extra_context通过年份:

from datetime import datetime
year = datetime.now().year

答案 1 :(得分:0)

您的核心问题是使用通用视图 - http://stdout.be/2010/05/25/generic-views-suck/

def post_list(request, page=0, paginate_by=1, **kwargs):
    page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by)
    queryset = Post.objects.published()
    paginator = Paginator(queryset, page_size) 
    objects = paginator.page(page)

    #This stuff is only necessary if you aren't trapping page in the URL conf
    #page = request.GET.get('page')
    #try:
    #    objects = paginator.page(page)
    #except PageNotAnInteger:
    #    # If page is not an integer, deliver first page.
    #    objects = paginator.page(1)
    #except EmptyPage:
    #    # If page is out of range (e.g. 9999), deliver last page of results.
    #    objects = paginator.page(paginator.num_pages)

    return render_to_response('mytemplate.html', {"objects": objects, "year": datetime.now().year}, context=RequestContext(request))

与原始版本相比,您宁愿维护或扩展哪些代码?