单页上多种表单的优雅解决方案

NFi*_*ano 2 django ajax postback get django-forms

我正在构建一个Web应用程序(在Django中),它将接受搜索条件并显示报告 - 一旦用户对结果感到满意,将标准和对这些对象的引用保存回数据库.

我遇到的问题是找到一个优雅的解决方案,有两种形式:

  1. 显示(GET)其标准的结果.
  2. 输入一些描述,然后将所有内容保存(POST)回数据库.

我倾向于使用AJAX获取GET内容和POST保存,但我想确保首先没有更优雅的解决方案.

Xav*_*osa 6

在实现ajax之前,我将尝试使表单在禁用javascript的情况下工作.2个表单可以指向相同的视图.对于路由操作,您可以使用填充<button type="submit">name value属性的标记,而不是<input type="submit">.

2表格模板

<form action="{% url your-url %}" method="get">
  <input type="text" name="q" value="{{ q }}">
  <button type="submit" name="action" value="search">Search</button>
</form>

{% if entries %}
  ...
  <form action="{% url your-url %}" method="post">
    <input type="hidden" name="q" value="{{ q }}">
    <button type="submit" name="action" value="save">Save entries</button>
  </form>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

不那么丑陋的表格模板

<form action="{% url your-url %}" method="post">
  <input type="text" name="q" value="{{ q }}">

  <button type="submit" name="action" value="search">Search</button>

  {% if entries %}
    ...
    <button type="submit" name="action" value="save">Save entries</button>
  {% endif %}
</form>
Run Code Online (Sandbox Code Playgroud)

然后,将"动作"捕捉到您的视图中,就像这段代码一样(未经过测试)

def your_view(request, *args, **kwargs):
    action = request.REQUEST.get('action', None)
    if request.method == 'POST' and action == 'save':
        # do the save stuff
    elif action == 'search':
        # no need to check if it's a GET
        if request.REQUEST.get('q', None):
            # do the display stuff
        else:
            # q required, maybe push a warning message here
    else:
        # default stuff

    return # the response ...
Run Code Online (Sandbox Code Playgroud)

然后你可以一些ajax