ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # 添加功能 ~~~ 1.根据上面两篇文章,我们已经成功搭建了一个博客基础页面,现在我们给它添加功能 ~~~ >[danger] ##### 添加一个文章搜索功能 ~~~ 1.接受前台穿过来的值,做 title = self.request.GET.get('query') 查询关键字 2.重写get_queryset(self) 进行搜索 3.重写 get_context_data(query=query) 其中利用**kwargs 原来,自动将query=query 填充 ~~~ ~~~ class IndexView(BasePostsView): def get_queryset(self): qs = super(IndexView, self).get_queryset() title = self.request.GET.get('query') if title: return qs.filter(title__icontains =title) return qs def get_context_data(self, **kwargs): query = self.request.GET.get('query') if query: return super(IndexView, self).get_context_data(query=query) return super(IndexView, self).get_context_data() ~~~ * 解决页面上form 表单样式 ~~~ 1.搜索的input 传值 用name 问题 ~~~ ~~~ <form action="/" method="GET" class="input-group search"> <div class="input-group search"> <input name="query" type="text" class="form-control" placeholder="Search for..." aria-label="Search for..."> <span class="input-group-btn"> <button class="btn btn-secondary" type="button">Go!</button> </span> </div> </form> ~~~ * 解决分页显示问题 ~~~ 1.增加判断,判断当前是否做搜索的分页 ~~~ ~~~ {% if page_obj.has_previous %} {% if query %} <a href="?page={{ page_obj.previous_page_number }}&query={{ query }}">上一页</a> {% else %} <a href="?page={{ page_obj.previous_page_number }}">上一页</a> {% endif %} {% endif %} Page {{ page_obj.number }} of {{ paginator.num_pages }}. {% if page_obj.has_next %} {% if query %} <a href="?page={{ page_obj.next_page_number }}&query={{ query }}">下一页</a> {% else %} <a href="?page={{ page_obj.next_page_number }}">下一页</a> {% endif %} {% endif %} ~~~ >[danger] ##### 用户文章过滤 ~~~ class AuthorView(BasePostsView): def get_queryset(self): author_id = self.kwargs.get('author_id') qs = super(AuthorView, self).get_queryset() if author_id: qs = qs.filter(owner_id=author_id) return qs ~~~ * url 增加一个新的跳转 ~~~ url(r'^author/(?P<author_id>\d+)/$', AuthorView.as_view(), name="author"), ~~~ * 页面对用户连接补充 ~~~ 作者:<a class="nav-link post-element-nav" href="{% url 'author' post.owner_id %}">{{ post.owner.username }}</a> ~~~