您的位置:首页 > 编程语言 > Go语言

Django实战之增加链接

2021-04-22 23:27 886 查看


上面完成的功能
首页
分类列表页面
标签列表页面
博文详情页面

还有
搜索结果页面
作者列表页面
侧边栏的热门文章
文章访问统计
友情链接页面
评论模块

增加搜索和作者过滤

需求
根据搜索关键词搜索文章和展示指定作者的文章列表
这个任务和前面的类似都需要根据某种条件过滤文章
根据之前写好的类视图
很容易实现

增加搜索功能

这里可以根据titile和desc作为关键词检索对象;
其实很简单,
只要根据控制好的数据源
而在IndexView中,控制数据源的部分由get_queryset方法实现,因此我们在views.py中增加如下代码

from django.db.models import Qclass SearchView(IndexView):
    def get_context_data(self,**kwargs):
        context=super().get_context_data()
        context.update({"keyword":self.request.GET.get("keyword","")})
        return context    def get_queryset(self):
        queryset=super().get_queryset()
        keyword=self.request.GET.get("keyword")
        if not keyword:
            return queryset        return queryset.filter(Q(title_icontains=keyword)|Q(desc_icontains=keyword))

接着配置urls.py 在url中引入SearchView然后增加如下代码

from blog.views import SearchView#省略其他代码re_path("^search/$",SearchView.as_view(),name="search"),

增加作者页面
在blog/view.py中添加如下代码

class AuthorView(IndexView):
    def get_queryset(self):
        queryset=super().get_queryset()
        author_id=self.kwargs.get("owner_id")
        return queryset.filter(owner_id=author_id)

相对搜索来说只需要控制数据源,如果要调整展示逻辑可以通过重写get_context_data来完成
在urls.py中增加

re_path('^author/(?P\d+)$',AuthorView.as_view(),name="author"),

将.html 中有作者一行中的post_detail 中替换为author
增加友联页面
在博客世界中,博主相互交换友链是一种很常见的方式,友链的另外一个作用是可以帮助每个博主把自己的博客都串联起来
前面已经写好了,后台录入内容的部分是可以用的,这里只需要把数据拿出来展示即可
处理逻辑和之前一样,我们只需要继承ListView即可,但要基于同一套模板,因此公用的数据还是 需要的 所以要同事继承CommonViewMixin
config/views.py中的代码如下

from django.views.generic import ListViewfrom blog.views import CommonViewMixinfrom .models import Link# Create your views here.class LinkListView(CommonViewMixin,ListView):
    queryset=Link.objects.filter(status=Link.STATUS_NORMAL)
    template_name="config/links.html"
    context_object_name="link_list"

接着在urls.py中添加如下路由
将原来的

re_path('^links/$',links,name="links"),

替换为

#记得修一下包from config.views import LinkListView
re_path('^links/$',LinkListView.as_view(),name="links"),

然后新增模板testblog/testblog/themes/new_theme_one/templates/config/links.html
代码如下

{% extends "blog/base.html" %}{% block title %}友情链接 {% endblock %}{% block main %}

    <table class="table">
    <thead>
    <tr>
        <th scope="col">#
        <th scope="col">名称</th>
        <th scope="col">网址</th>
    </tr>
    </thead>
    <tbody>
    {% for link in link_list %}
        <tr>
        <th scope="row">
            <td>{{ link.title }}</td>
            <td><a href="{{ link.href }}">{{ link.href }}</a></td>
        </th>
        </tr>
    {% endfor %}
    </tbody>
    </table>{% endblock %}

               

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: