how to retrieve input value of html form if form i

2019-09-21 19:45发布

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>

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)

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)

How can i use form.py

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

Thanks.

1条回答
老娘就宠你
2楼-- · 2019-09-21 19:52

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>

View:

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 will be a list of input values from your form (or an empty list if form had zero input elements).

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

查看更多
登录 后发表回答