[Python #17] [Django #10] 搜索功能,还差UI

pixabay

给搜索穿上UI,先简单尝试HTML的form,能力有限,只能先简单尝试。

添加 form

首先,在 django的 templates 文件夹下,给 base.html 添加 form 。

  1. action 值先用硬编码 /@june0620/search赋值,账号应该用变量,但目前还不知道怎么用变量。 没办法,谁让我是django初学者呢。
  2. method赋值get应该比post好点,因为是搜索功能。
  3. 创建三个 input 标签,命名为 tags, titles, texts 。
      <div>
          <p></p>
          <form action="/@june0620/search/" method="get">
              <label >Tags: </label>
              <input id="tags" type="text" name="tags" value="">
              <label >Titles: </label>
              <input id="titles" type="text" name="titles" value="">
              <label >Texts: </label>
              <input id="texts" type="text" name="texts" value="">
              <input type="submit" value="Search">
          </form>       
      </div>

大致就是这个模样,因还没装CSS,只能这样了,焦点先放在功能上。👇

设置 URL

从 form的 action 收到的值需要设置在 urls.py 下。这部分我懂怎么用变量,哈哈。
url pattern 若匹配就调用 views.py的 SearchPosts 类。

    path('@<slug:account>/search/', SearchPosts.as_view(), name='search'),

处理 form 参数及搜索

从 form 传到的 query string 需要我用 split(',')转为list 并存到 query dictionary。
这样可以在 UI 用逗号搜索多个关键词,结果会更丰富。
(目前还是临时性的实现,等日后实现完UI,再研究。)

class SearchPosts(ListView):
    template_name = 'album.html'
    context_object_name = 'all_posts'

    def get(self, request, *args, **kwargs):
        query = {
            'tags': request.GET.get('tags').split(','),
            'titles': request.GET.get('titles').split(','),
            'texts': request.GET.get('texts').split(',')
        }
        se = Search(account=kwargs['account'], query=query)
        self.queryset = se.search_posts()
        return super().get(request, *args, **kwargs)

结果

[Cookie 😅]
Python 3.7.4
Django 2.2.4
steem-python 1.0.1
goorm IDE 1.3

Sort:  

Upvoted by GITPLAIT!


We share 80 % of the curation rewards with the delegators.We have a curation trial on Hive.vote. you can earn a passive income by delegating to @gitplait

To delegate, use the links or adjust 10HIVE, 20HIVE, 50HIVE, 100HIVE, 200HIVE, 500HIVE, 1,000HIVE, 10,000HIVE, 100,000HIVE

Join the Community and chat with us on Discord let’s solve problems & build together.

I have picked your post for my daily hive voting initiative, Keep it up and Hive On!!


Have a good day😀Thank you so much, @chitty 👍