def get(self, request): '''显示首页''' # 如果是认证用户则显示自己的文章,否则显示管理员的文章 # context = cache.get('index_page') if True: if request.user.is_authenticated: articles = Article.objects.filter( user_id=request.user.id).filter( is_delete=False).order_by('-create_time') # 用户文章数量不够则用管理员的文章补齐4个 if len(articles) < 4: x = 4 - len(articles) articles1 = Article.objects.filter(user_id=1).filter( is_delete=False).order_by('-create_time')[:x] new_articles = chain(articles, articles1) else: new_articles = articles[:4] else: articles = Article.objects.filter(user_id=1).filter( is_delete=False).order_by('-create_time') new_articles = articles[:4] types = ArticleType.objects.all() today = datetime.datetime.today() # 获取最近一年的活动 user = request.user if request.user.is_authenticated else 1 activitys = cache.get('activitys') if not activitys: last_year = today - datetime.timedelta(days=359) #365-6 last_year = get_last_monday(last_year) try: a = Activity.objects.get(user=user, activity_date=today) except: Activity.fake_activity(days=1) finally: tomorrow = today + datetime.timedelta(days=1) activitys = Activity.objects.filter( user=user, activity_date__range=( last_year, tomorrow)).order_by('activity_date') cache.set('activitys', activitys, 60 * 60 * 24) # 获取每日一句 quote = cache.get('quote') if not quote: try: quote = Quote.objects.get(date=today) except: date = today.strftime('%Y-%m-%d') content, translation, author = get_quote(date=date) quote = Quote.objects.create(date=today, quote=content, translation=translation, source=author) quote.save() cache.set('quote', quote, 60 * 60 * 24) for a in articles: a.content = markdown.markdown( a.content, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' ]) # 分页器,若是首页则激活动态这个panel, # 要是有 page 参数则是文章选项卡 paginator = Paginator(articles, 12) page = request.GET.get('page') if page is None: isindex = True page = 1 else: isindex = False articles = paginator.page(page) page = int(page) # 显示前后5页 a = paginator.num_pages if a <= 5: start = 1 end = a else: if page < 5: start = 1 end = 5 elif page > a - 5: start = a - 4 end = a else: start = page - 2 end = page + 2 page_list = list(range(start, end + 1)) # 统计新增文章数量 article_counter = Article.objects.filter( create_time__gt=today).count() articletype_counter = ArticleType.objects.filter( create_time__gt=today).count() if request.user.is_authenticated: notes = Note.objects.filter(owner_id=request.user.id)[:5] else: notes = Note.objects.filter(owner_id=1)[:5] context = { 'quote': quote, 'new_articles': new_articles, 'articles': articles, 'isindex': isindex, 'types': types, 'activitys': activitys, 'article_counter': article_counter, 'articletype_counter': articletype_counter, 'page_list': page_list, 'notes': notes, } # cache.set('index_page',context,60) return render(request, 'index.html', context)
def generate_user_activity(): from user.models import Activity Activity.fake_activity(days=1)