简体   繁体   English

Django request.POST 从输入中获取数据

[英]Django request.POST get data from input

In HTML在 HTML 中

<form method='post'>
{% csrf_token %}
{{form.name}}
{{form.email}}
<textarea name='message'>{{form.message}}</textarea>
<button type='submit'>Send</button>
</form>

How I can get the message data from my textarea in my view?如何从视图中的文本区域获取消息数据? Or the right way is put {{form.as_p}} in form?或者正确的方法是将 {{form.as_p}} 放入表单中? Please help请帮忙

Above answer is perfectly alright if you want this on view.如果你想看到这个,上面的答案是完全可以的。 Another safe method is request.POST.get('message') it will return None instead of error message, if it's available.另一个安全的方法是request.POST.get('message')如果可用,它将返回None而不是错误消息。

But, you want it on template then you can use但是,您希望在模板上使用它,然后您可以使用

{{ form.data.message }}

request.POST is basically a dictionary returned. request.POST基本上是一个返回的字典。 It contains csrfmiddlewaretoken and all form data with name specified as key in the request.POST dict.它包含csrfmiddlewaretoken和名称指定为request.POST字典中的键的所有表单数据。

So, as per your form, you can get the message data from textarea by simply writing因此,根据您的表单,您可以通过简单地编写从 textarea 获取消息数据

message_data = request.POST['message']

in view.py .view.py

If you want to display form in your style then do it manually.如果您想以您的风格显示表单,请手动进行。 Otherwise, django provides few techniques to render form, and they are as follows:否则,django 提供的渲染表单的技术很少,它们如下:

{{ form.as_table }} will render form as table cells wrapped in <tr> tags, {{ form.as_table }}将表单呈现为包裹在<tr>标签中的表格单元格,

{{ form.as_p }} will render form wrapped in <p> tags, {{ form.as_p }}将呈现包裹在<p>标签中的表单,

{{ form.as_ul }} will render form wrapped in <li> tags. {{ form.as_ul }}将呈现包裹在<li>标签中的表单。

Now, it depends upon you, how you want your form to look on page.现在,这取决于您希望表单在页面上的外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM