ETHAN avatar

[Python #18] [Django #11] form action 添加变量(副题:搜索他人搜索)

june0620

Published: 12 Sept 2020 › Updated: 12 Sept 2020[Python #18] [Django #11] form action 添加变量(副题:搜索他人搜索)

[Python #18] [Django #11] form action 添加变量(副题:搜索他人搜索)

pixabay

上回,有一个地方我用硬编码,因我不会用变量。

action 值先用硬编码 /@june0620/search赋值,账号应该用变量,但目前还不知道怎么用变量。 没办法,谁让我是django初学者呢。

当时用我的账号硬编码,所以无法搜索他人的文章。今天解决这个问题吧。
从URL获取账号赋值给action参数。幸好Django提供获取URL的方法{{ request.path }},通过Template filters创建一个过滤器应该可以过滤账号了。

templatetags

在 templatetags 文件夹 > post_extras.py文件里注册一个过滤器。过滤的方法用正规表达式最好不过,但我不太会用正规表达式。哎~没事儿,学吧。

经过我精心的搜索,搜出了一个非常好用的正规表达式检查器。https://regex101.com/r/cO8lqs/4 就用你了~

import re
...
...

@register.filter
def get_account_form_url(path: str):
    account = re.search(r'@[a-z0-9-.]*', path)
    print(path)
    print(account.group(0))
    return account.group(0) if account else None

alt

base.html

在 base.html 载入过滤器, form action 也改用过滤器就OK了。

{% load post_extras %}
...
...

          <form action="/{{ request.path | get_account_form_url }}/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>  

alt

结果

哈哈,现在可以搜索萍萍(annepinkHive account@annepink)的熊孩纸文章了。😄
alt


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

参考文章:
https://medium.com/@chrisjune_13837/%EC%A0%95%EA%B7%9C%EC%8B%9D-%ED%8A%9C%ED%86%A0%EB%A6%AC%EC%96%BC-%EC%98%88%EC%A0%9C%EB%A5%BC-%ED%86%B5%ED%95%9C-cheatsheet-%EB%B2%88%EC%97%AD-61c3099cdca8

Leave [Python #18] [Django #11] form action 添加变量(副题:搜索他人搜索) to:

Written by

Read more #cn posts


Best Posts From ETHAN

We have not curated any of june0620's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ETHAN