如果表单在django for loop中,如何检索html表单的输入值 [英] how to retrieve input value of html form if form is in django for loop

查看:121
本文介绍了如果表单在django for loop中,如何检索html表单的输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题.下面有一个django模板ip_form.html.

I got a situation.I have a django template ip_form.html given bellow.

<form method = "GET">
  {% for val in value_list %}
    <input type='text' value = '{{ val }}'> {{ val }}</input>
  {% endfor %}
</form>

我想告诉你,我不知道value_list中的val数(可能为零).因此,可能不使用django form.py(而且我在某个特定视图功能的特定时间内获得了价值,即我不知道天气会一直发生)

I want to tell you that, I have unknown no of val in value_list(may be zero). So may not use django form.py( and also I am getting value in certain time of a particular view function, i.e. don't know weather it will occur all time)

让我们在views.py中发言

Let's say in views.py

def view1(request):
 value_list = [1,2,3,4,5] # it will change every time view1 will get request
 if request.method == "GET":
    # i want to retrieve here post
 return render ('ip_form.html','value_list':value_list)

我如何使用form.py

How can i use form.py

那么我该如何找回它.您可以参考我的post方法.(它不是敏感数据,因此get方法没有问题)

So how can I retrieve it. You can refer me post method.(Its not a sensitive data so no problem with get method)

谢谢.

推荐答案

您需要在输入中添加一个name属性,然后您可以使用该名称使用

You need to add a name attribute to your inputs, and then you can use this name to retrieve a list of values, using Django QueryDict getlist method:

HTML:

<form method="POST">
  {% for val in value_list %}
    <input type='text' value='{{ val }}' name='my_list'>{{ val }}</input>
  {% endfor %}
</form>

查看:

def view1(request):
    value_list = [1,2,3,4,5] # it will change every time view1 will get request
    if request.method == "POST":
        values_from_user = request.POST.getlist('my_list')
    return render ('ip_form.html', 'value_list': value_list)

values_from_user将是表单输入值的列表(如果表单具有零个input元素,则为空列表).

values_from_user will be a list of input values from your form (or an empty list if form had zero input elements).

请注意,我将您的表单方法更改为POST,因为否则您认为request.method测试将毫无意义.

Please note that I changed your form method to POST, because otherwise the request.method test in your view would be meaningless.

这篇关于如果表单在django for loop中,如何检索html表单的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆