I'm building a news website.I need display 48 hours most viewed news, this part is in the detail.html page. Now I'm using this method.
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
News.objects.filter(id=news_pk).update(pv=F('pv') + 1)
time_period = datetime.now() - timedelta(hours=48)
host_news=news.objects.filter(date_created__gte=time_period).order_by('-pv')[:7]
return render(request, "news_detail.html", {
'news': news,
'host_news' : host_news
})
It works very well, but my question is ,in oder to use cache conveniently,I want to separate the hot_news functions from def newsDetailView.
I have tried :
def hot_news(request):
time_period = datetime.now() - timedelta(hours=48)
hot_news =News.objects.filter(add_time__gt=time_period).order_by('-pv')[:7]
return render(request, "news_detail.html", {
'most_viewedh': most_viewedh
})
However I can't get the data, in detail.html
. I guess the issue is because the url.
the link of the detail.html
from the index.html
is
<a href="{% url 'news:news_detail' news.pk %}">
news:news_detail
is the url of view def newsDetailView
So the url is directly to def newsDetailView and has nothing two do with def hot_news.
What should I do, so that I can render the data from def hot_news to the same page as def newsDetailView does?