简体   繁体   English

Django,从POST获取值

[英]Django, Getting a value from a POST

I have in my template: 我的模板中有:

This is passed by {{form}}

    <form action="" method="POST">
        Inicio: <input type="text" id="start">
        <input type="submit" value="Sned" >
     {% csrf_token %}
    </form>

Then in the views.py 然后在views.py

def test(request):

    if request.method != 'POST':
        context = {'form': 'by GET'}
        return render(request, 'test.html', context)
    else:

        if 'start' in request.POST:
            start = request.POST['start']
        else:
            start = False


    context = {'form': start}
    return render(request, 'test.html', context)

It seems that always return False 似乎总是返回False

If I dont check the existance of the key I have this error: 如果我不检查密钥的存在,则会出现此错误:

MultiValueDictKeyError 

And the erropage says : "'start'" (single plus double quotes) erropage上说:“'开始'”(单引号和双引号)

id is intended for javascript and css purposes. id是用于javascript和CSS的目的。 For variables that are important on server side, you should use name tag. 对于在服务器端很重要的变量,应使用name标签。

<input type="text" id="start" name="start">

You need to add a name attribute in your input, so when you are getting the POST data it will be found. 您需要在输入中添加名称属性,以便在获取POST数据时将找到它。

<form action="" method="POST">
    Inicio: <input type="text" id="start" name="start">
    <input type="submit" value="Sned" >
    {% csrf_token %}
</form>

Also I recommend you to do the following change in your view: 另外,我建议您在视图中进行以下更改:

Replace 更换

request.POST['start']

by: 通过:

request.POST.get('start')

So, if the field is not found, it will be reassigned whith a None value. 因此,如果找不到该字段,则将使用None值重新分配该字段。

添加名称

<input type="text" name="start" id="start">

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

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