【问题标题】:Passing parameters using action tag in HTML在 HTML 中使用动作标签传递参数
【发布时间】:2020-07-17 18:48:01
【问题描述】:

我正在使用 Tornado (python),我的处理程序采用这种格式。

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            url(r'/', MainHandler, name="main_handler"),
            url(r'/user', UserHandler, name="user_handler"),
            url(r'/users', UserListHandler, name="user_list_handler"),
            url(r'/profile/(?P<username>\w+)', UserProfileHandler, name="user_profile_handler"),    
        ]
        settings = dict(
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            static_path = os.path.join(os.path.dirname(__file__),"static"),
            debug = True)
        self.db = client['user_db']
        super().__init__(handlers, **settings)

我在着陆页上的 HTML 代码是

<h1>INFO DB</h1>
    <p>Search via username...</p>
    <form method="get" action="{% url 'user_profile_handler' find_username %}">
        <p>Enter Username<br>
        <input rows=1 cols=20 name="find_username"></p>
        <input type="submit">
    </form>
    <br>

现在我的目标是当我点击提交按钮时, 我被重定向到页面'/profile/{username} 例如:如果搜索栏中的用户名是“abcd”,我应该在按下提交时重定向到 /profile/abcd。 HTML中form标签的action属性要放什么?

【问题讨论】:

    标签: python html django web tornado


    【解决方案1】:

    好吧,django 的 Jinja 标签(如 {% url %})是在 get 时估计的,因此您必须将 find_username 实际传递给您无法使用这些方案的上下文,因为您在页面加载后获取它。要实现您想要做的就是制作一个处理这种情况的视图。在伪代码中它看起来像这样

    def view(request):
    
        form = username_form()
    
        if request.method == "POST":
            form = username_form(request.POST)
            if form.is_valid():
                user = get_object_or_404(User, username=form.cleaned_data['username'])
                return redirect('profile', user.id)
    
        return render(request, ...., {'form': form})
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2021-02-02
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多