访问Django中post方法的表单数据

时间:2017-02-21 05:04:44

标签: python django

我想访问views.py中的post方法数据。我遵循使用纯html的程序而不是 Django表单类。我尝试了解决方案 MultiValueDictKeyError in Django但仍然没有用。帮帮我

的index.html

Copy

views.py

<form action="{% url "Sample:print" %}" method="post">
    {% csrf_token %}
    <input type="text" placeholder="enter anything" id="TB_sample"/><br>
    <input type="submit" value="submit">
</form>

我尝试了所有评论类型。我仍然遇到很多错误。这些解决方案都不起作用。

2 个答案:

答案 0 :(得分:3)

重命名函数的打印名称(称为def print)。永远不要命名python内置函数的函数。

首先,您必须为输入字段指定名称以获取post参数。像,

<input type="text" placeholder="enter anything" name="TB_sample" id="TB_sample"/>

然后,您输入了

value=request.POST['TB_sample']

在django函数中。如果没有名为TB_sample的参数,则抛出 MultiValueDictKeyError 。总是写,

value=request.POST.get('TB_sample')

输出None而不是抛出错误。

答案 1 :(得分:0)

'name'输入: <input name="firstname" type="text" value="firstname">

在Django( views.py

def register_form(request):
    if request.method =='POST':
        name = request.POST['firstname']
        print(name)

    return redirect('/')
相关问题