python - 如何在 Django 2.1 中使用多种形式?

标签 python html django

很抱歉提出类似的问题,但其他类似的问题/答案对 Django 2 没有帮助。

问题: 我有两个 Action ,一个是将一些数据显示为表格。 在第二种形式中,我编辑此数据并使用数据库中的 Django 将其保存为表格。这是一些代码:

simple_upload.html

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile" value="formOne">
    <button class="btn btn-primary" type="submit">Upload</button>
</form>

第二种形式:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="hidden" name="mytable" value="formTwo">
    <table class="table" border="1" id="tbl_posts">
    <thead>
      <tr>
...

    </tbody>
    </table>
    <input type="submit" value="Submit">
 </form>

views.py

def simple_upload(request):
    if request.method == 'POST':
    ...
    if request.is_ajax():
        return render(request,
                    'project/simple_upload.html',
                    {'section': 'project', 'lines': zipped})
    return render(request,
                'project/list.html',
                {'section': 'project', 'lines': zipped})
return render(request, 'project/simple_upload.html')

urls.py:

urlpatterns = [
...
    path('', views.simple_upload, name='list'),
...
]

list.html:

...
{% include "project/simple_upload.html" %}
...

在这种情况下,只有第一个 form 有效,第二个失败。

问题 1: 我可以做 if request.method == 'POST' and formOne in request.POST:", 我试试但它根本没有反应。

问题 2:如何编写两个方法并使用 urls.py 分配它们?

最佳答案

要在表格中显示数据,您可以在 Django 中尝试 Tables2,这可能会让您更轻松

同样在您的情况下,您可能需要为不同的表单制作不同的 View ,因为它们都发出 POST 请求,因此很难区分。

您可以通过在表单标签中指定 action 属性轻松地做到这一点。

表格 1

<form id="form1" method="post" action="view/for/form/1" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>

表格 2

<form method="post" action = "view/for/form/2" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
  <tr>
...

</tbody>
</table>
<input type="submit" value="Submit">
 </form>

稍后您可以使用 json 响应重定向以避免刷新页面

在你的 urls.py 添加

url('view/for/form/2', save_form, name='save'),

在你的 views.py 中

def save_form(request):
    #your save logic using request.post
    return redirect('your/current/url')

关于python - 如何在 Django 2.1 中使用多种形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57952946/

相关文章:

python - Django View 还可以由什么组成?

python - 从 Pandas 中两列的文本的第二部分创建一列

python - 如何在 python 中将十进制 0 打印为 000

javascript - jQuery 在中途改变 CSS 关键帧动画的方向

javascript - 在 iframe 中创建 DOM 元素

python - 将 Django 与亚马逊的数据库集成 'SimpleDB'

python - 我的 UTF8 字符串中的 Django\u 字符

python - Python 标志是什么意思?

python - 测试 SSH 私钥密码(暴力破解)

javascript - 使用点击功能检查多个div中的数据属性值