视图缓存
缓存整个视图返回的数据
from django.views.decorators.cache import cache_page
from zanhu.articles import views
app_name = "articles"
urlpatterns = [
# 在这里配置对于试图的缓存--缓存5分钟
path("<str:slug>/", cache_page(5 * 60)(views.ArticleDetailView.as_view()), name="article"),
]
只缓存视图中的某一个方法
# 只缓存get请求返回的结果, 不缓存post请求返回的结果
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
@method_decorator(cache_page(60 * 60), name="get")
class ArticleCreateView(LoginRequiredMixin, CreateView):
"""发表文章==>填写表单==>使用form"""
model = Article
form_class = ArticleForm
template_name = "articles/article_create.html"
message = "您的文章已创建成功!"
前端模板片段的缓存(导航栏)
request.user.username : 实现针对不同用户, 缓存不一样的数据
{% load static thumbnail compress cache %}
<!DOCTYPE html>
{% cache 3600 sidebar request.user.username %}
<nav class="navbar fixed-top navbar-expand-sm bg-light"...>
{% endcache %}
评论区