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

in #hive-105017last month



添加 form

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

  1. action 值先用硬编码 /@june0620/search赋值,账号应该用变量,但目前还不知道怎么用变量。 没办法,谁让我是django初学者呢。
  2. method赋值get应该比post好点,因为是搜索功能。
  3. 创建三个 input 标签,命名为 tags, titles, texts 。
          <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">


设置 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 用逗号搜索多个关键词,结果会更丰富。

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


Upvoted by GITPLAIT!

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

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!!

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