使用django开发博客过程记录3——博客侧栏实现

说起这个侧栏真是苦恼我很长时间,一开始以为和之前的一样传递额外参数就可以了就像下面这样:

class IndexView(ListView):
    template_name = 'apps/index.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = Article.objects.filter(status='p')
        return article_list

    def get_context_data(self, **kwargs):
        context = super(PublisherDetail, self).get_context_data(**kwargs)
    context['category'] = Category.objects.all()
        return context

但是自己一想,这个只是渲染到了首页,那如果我要是跳转导一篇博客的详细页面的时候怎么办,还要在博客详细页面也渲染一个category上下文参数吗?后来的github上看了一下别人的代码才恍然大悟,原来模板中的内容不只是通过上下变量进行渲染,还可以有其他的方式,一个叫 django.template.RequestContext的类,详细内容请看The Django Book第九章

我们接下来进行配置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'apps.context_processors.sidebar', # sidebar context variables
            ],
        },
    },
]

看到了我们增加了 apps.context_processors.sidebar,之后只要我们增加一个context_processors.py在apps文件夹下就行(apps为我们的应用文件夹)。以下是我们的context_processors.py内容:

# -*- coding:utf-8 -*-
from django.db.models import Count
from .models import Article, Category, Tag


def sidebar(request):
    # 取出构造侧栏时需要用到的信息.
    recent_posts = Article.objects.filter(status__exact='p').order_by('create_time')[:3]
    unregular_dates = Article.objects.values_list('create_time').order_by('-create_time')
    category_list = Category.objects.filter(article__status='p').annotate(number_of_articles=Count('article'))
    tag_list = Tag.objects.filter(article__status='p').annotate(number_of_articles=Count('article'))

    # 初始化构造归档时用到的数据.
    dates = []
    temp_dates = []
    month_count = 1
    piece = {}
    dates_tuple = [(date[0].year, date[0].month) for date in unregular_dates]

    """
    如果一个元组信息不再temp_dates中,
    那么就将其相关信息插入导返回结果中,
    并且将记录每月博客数量变量month_count设置为1
    """
    for date in dates_tuple:
        month_count += 1

        if date not in temp_dates:
            piece['year'] = date[0]
            piece['month'] = date[1]
            piece['count'] = month_count

            temp_dates.append(date)
            dates.append(piece)
            month_count = 1

    return {
        'recent_posts': recent_posts,
        'dates': dates,
        'category_list': category_list,
        'tag_list': tag_list
    }

 以下是html代码:

 1 <aside class="col-md-4">
 2     <div class="widget widget-recent-posts">        
 3         <h3 class="widget-title">Recent Posts</h3>        
 4         <ul>
 5             {% for post in recent_posts %}
 6             <li>
 7                 <a href="{url 'apps:detail' post.id}">{{ post.title }}</a>
 8             </li>
 9             {% endfor %}
10         </ul>
11     </div>
12 
13     <div class="widget widget-archives">        
14         <h3 class="widget-title">Archives</h3>
15         {% regroup dates by year as year_list %}        
16         <ul>
17             {% for year in year_list%}
18             <li>
19                 <a href="#">{{ year.grouper }}年</a>
20                 <ul>
21                     {% for month in year.list%}
22                     <li>
23                         <a href="#">{{ month.month }}月({{ month.count }})</a>
24                     </li>
25                     {% endfor %}
26                 </ul>
27             </li>
28             {% endfor %}
29         </ul>
30     </div>
31 
32     <div class="widget widget-category">        
33         <h3 class="widget-title">Category</h3>
34         <ul>
35             {% for cat in category_list %}
36             <li>
37                 <a href="#">{{ cat.name }}({{ cat.number_of_articles }})</a>
38             </li>
39             {% endfor %}
40         </ul>
41     </div>
42 
43     <div class="widget widget-category">        
44         <h3 class="widget-title">Tags</h3>        
45         <ul>
46             {% for tag in tag_list %}
47             <li>
48                 <a href="#">{{ tag.name }}</a>
49             </li>
50             {% endfor %}
51         </ul>
52     </div>
53 </aside>
View Code

以上就是侧栏开发的过程,逻辑还是比较简单的,主要是熟悉django的使用,希望对大家在学习django过程中有所帮助。

原文地址:https://www.cnblogs.com/selfimprovement/p/5953584.html