Django實戰之增加鏈接

書接 https://blog.csdn.net/weixin_32759777/article/details/104719760
上面完成的功能
首頁
分類列表頁面
標籤列表頁面
博文詳情頁面

還有
搜索結果頁面
作者列表頁面
側邊欄的熱門文章
文章訪問統計
友情鏈接頁面
評論模塊

增加搜索和作者過濾

需求
根據搜索關鍵詞搜索文章和展示指定作者的文章列表
這個任務和前面的類似都需要根據某種條件過濾文章
根據之前寫好的類視圖
很容易實現

增加搜索功能

這裏可以根據titile和desc作爲關鍵詞檢索對象;
其實很簡單,
只要根據控制好的數據源
而在IndexView中,控制數據源的部分由get_queryset方法實現,因此我們在views.py中增加如下代碼

from django.db.models import Q

class 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<owner_id>\d+)$',AuthorView.as_view(),name="author"),

將.html 中有作者一行中的post_detail 中替換爲author
增加友聯頁面
在博客世界中,博主相互交換友鏈是一種很常見的方式,友鏈的另外一個作用是可以幫助每個博主把自己的博客都串聯起來
前面已經寫好了,後臺錄入內容的部分是可以用的,這裏只需要把數據拿出來展示即可
處理邏輯和之前一樣,我們只需要繼承ListView即可,但要基於同一套模板,因此公用的數據還是 需要的 所以要同事繼承CommonViewMixin
config/views.py中的代碼如下

from django.views.generic import ListView
from blog.views import CommonViewMixin
from .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>
        <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 %}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章