[Python #17] [Django #10] 搜索功能,还差UI
hive-105017·@june0620·
0.000 HBD[Python #17] [Django #10] 搜索功能,还差UI
pixabay https://cdn.pixabay.com/photo/2019/05/14/17/07/web-development-4202909_1280.png 给搜索穿上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> ``` <p>  <p> 大致就是这个模样,因还没装CSS,只能这样了,焦点先放在功能上。👇  ##### 设置 URL 从 form的 action 收到的值需要设置在 urls.py 下。这部分我懂怎么用变量,哈哈。 url pattern 若匹配就调用 views.py的 SearchPosts 类。 ``` path('@<slug:account>/search/', SearchPosts.as_view(), name='search'), ``` <p>  ##### 处理 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) ``` <p>  ##### 结果  <p>  **[Cookie 😅]** Python 3.7.4 Django 2.2.4 steem-python 1.0.1 goorm IDE 1.3
👍 toni.pal, donekim, laissez-faire, nokodemion, roseofmylife, slowwalker, daath, moneytron, cpt-sparrow, itchyfeetdonica, kimzwarch, veronicalee, udabeu, tokenindustry, suonghuynh, smartvote, ravensavage, forecasteem, mafia.wallet, magicmonk, cnbuddy, wherein, tumutanzi, oldstone, coldhair, minloulou, lindalex, andrewma, changxiu, cherryzz, steemfriends, cnstm, ctime, tina3721, andyhsia, oldstone.sct, cnbuddy-reward, real3earch, logicforce, alphacore, lianjingmedia, lotusofmymom, jsj1215, yasu, julialee66, gerdtrudroepke, lucky2015, lupafilotaxia, minigame, steem-agora, shenchensucc, june0620, suhunter, melaniewang, zerofive, payroll, leslierevales, starrouge, dudream, coder-bts, bluengel, tipu, happy-soul, mia-cc, kryptogames, dappstats, cornavirus, cryptogambit, bartheek, jacuzzi, longer, gitplait, tykee, kamchore, bala41288, gghite, chitty, rafaelaquino,