---
# System prepended metadata

title: '[Django] - 玖-2、search_history view'
tags: [webdevelopment]

---

---
title: \[Django] - 玖-2、search_history view
tags: webdevelopment
---

本篇來完成search_history view
打開views.py輸入下面的程式碼

檢查使用者是否登入
若未登入則跳轉至登入頁面
若登入則取得該使用者曾經搜尋過的域名，並渲染到search_history的頁面
```code=python
# search_history view
def search_history(request):
    # 檢查使用者是否登入
    if request.user.is_authenticated:
        # 取得該使用者的域名物件
        domain_obj = Domain.objects.filter(user=request.user)
        for obj in domain_obj:
            print(obj.domain)
        # 渲染到search_history.html
        return render(request, 'ranking/search_history.html',
                      context={'search_history':domain_obj})
    else:
        return HttpResponseRedirect("login")
```

大家應該還記得，為了紀錄各域名和各關鍵字的名次，我們額外規劃了兩個頁面
keyword_history以及rank_history
這邊一併把他們完成
```code=python
# keyword_history view
# 需要把從search_history收到的域名傳到這裡
# 可以去search_history.html中找到url的地方，domain_name由那邊傳出
def keyword_history(request, domain):
    i = 0
    # 獲取使用者想看的域名
    domain_obj = Domain.objects.filter(user=request.user, domain=domain).prefetch_related("keywords")
    keywords_list = []
    print(domain_obj)
    for D_obj in domain_obj:
        # 獲取關鍵字並把它們都存到列表中
        print(f"{i}: {D_obj}")
        keyword_obj = D_obj.keywords.all()
        i+=1
        for K_obj in keyword_obj:
            keywords_list.append(K_obj.keyword)
    print(keywords_list)
    # 把從資料庫獲取的的資料選染到keyword_history.html
    return render(request, 'ranking/keyword_history.html',
                  context={"keywords_list":keywords_list,
                           "domain":domain})
```

rank_history view
```code=python
# rank_history view
def rank_history(request, domain, keyword):
    print(f"Domain name: {domain}")
    print(f"Keyword name: {keyword}")
    domain_obj = Domain.objects.filter(user=request.user, domain=domain).prefetch_related("keywords__rank_history")
    rank_list = []
    for D_obj in domain_obj:
        for K_obj in D_obj.keywords.filter(keyword=keyword):
            # 按照建立日期排序
            for R_obj in K_obj.rank_history.order_by("-created_at"):
                rank_list.append(R_obj.rank)
    print(rank_list)
    return render(request, 'ranking/rank_history.html',
                context={"rank_list":rank_list,
                        "keyword":keyword,
                        "domain":domain})
```

完成之後，就等我們把登入和註冊頁面完成再一起測試啦～

謝謝大家的收看！
如果有任何想法或是問題歡迎寄信到 chantinghsien@gmail.com
可以一起討論和分享新知