【问题标题】:Sending table data from html form to django views将表格数据从 html 表单发送到 django 视图
【发布时间】:2019-09-14 23:29:54
【问题描述】:

我有一个 html 表单,它有一个带有 th、td 和 POST 方法的表格,并且操作是针对 django 视图。如何将我的 td,th 值发送到 django 视图?

我尝试过使用输入类型文本,它可以工作,但我不想在我的第 td,th 行上使用任何输入类型。有没有办法直接从 django 视图访问 td 值?

html文件:

<form method="post" action="display">
{% csrf_token %}
<table name="resultsTable">
<th name="tableHeader">Name</th>
<td name="tableValue">Jon</td>
<button type="Submit">Display</button>
</table>
<form>

views.py:

@csrf_exempt
def display(request):
   if request.method=='POST':
      print(request.POST)

我想在显示功能中打印姓名,乔恩

【问题讨论】:

    标签: html django


    【解决方案1】:
    <form method="post" action="display">
    {% csrf_token %}
    <table name="resultsTable">
    <th name="tableHeader"><input type='text' value='Name' name='title_field_name' /></th>
    <td name="tableValue"><input type='text' value='Jon' name='data_field_name' />Jon</td>
    <button type="Submit">Display</button>
    </table>
    <form>
    

    【讨论】:

    • 感谢您的回复,但我已经尝试过这种方法,我希望这样做而不在 td 和 th 行中包含任何输入
    • 我认为你需要通过 ajax 而不是 Django 表单发回信息。您将显示类似&lt;th id="tableHeader" data-value="Name"&gt;Name&lt;/th&gt; 的行,然后在 JavaScript 中根据标签内的数据值设置您传回的数据。
    【解决方案2】:

    html文件:

    <form method="post" action="display">
        {% csrf_token %}
        <table name="resultsTable">
            <th name="tableHeader">Name</th>
            <td id="name" name="name">{{ form.name }}</td> # form.[name of your model or form atribute]
            <button type="Submit">Display</button>
        </table>
    <form>
    

    views.py:

    @csrf_exempt
    def display(request):
    template_name = 'people_list.html'
       form = YourForm()
    
       if request.method=='GET':
          context= {"form": form}
          return render(request, self.template_name, context)
    
       if request.method=='POST':
          form = YourForm(request.POST)
          if form.is_valid():
              form.save()
              context = {"form": form}
              return render(request, self.template_name, context)
          print(request.POST)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 2018-01-11
      相关资源
      最近更新 更多