Django具有相同名称的多个输入字段值 [英] Django multiple input field values with same name

查看:159
本文介绍了Django具有相同名称的多个输入字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助。如何使用同一个名称处理多个输入字段值的表单?只有一次查看,这实际上是基本问题的形式..另一​​个想法,我发现这种方法从



如何我处理这一切吗?目前,我正在使用< input type =radio... ,但是如果一次使用相同的名称,它将无法正常工作。但是如果我使用:< input type =checkbox... ,答案可以一次检查超过1个问题...



也许这样:

 < input type =radioname =answer- {{question.id}}> 

如何在视图中获得所有这些?



已解决



在我的测试中:

  {%在问题中的问题%} 
< input type =hiddenname =questionvalue ={{question.id}} />

{%for question.get_answers%}
< input type =radioname =answer - {{question.id}}value = {{answer.score}}>
{%endfor%}
{%endfor%}

views.py

  questions = request.POST.getlist('question')
答案= [request.POST ['answer - {}'。format(q)] for q in questions]

其结果:

  ['20','19','16','13' ,'11','10','9','8','1'] 
['5','2','3' '4','2','2']


解决方案

如果我理解你,你需要实现多项选择?
那么你可以在你的模板中做到这一点:

  {%for answer in answers%} 
< input type =checkboxname =answerid =answer {{forloop.counter}}value ={{answer.id} }>
{%endif%}

Andi在视图中:

  answer = request.POST.getlist('answer')
for el in answer:
pass


I need some help. How can I handle the form ,with multiple input field values, with same name? and only once view, this actually for basic questions form.. another idea I found this method from https://stackoverflow.com/a/478406/6396981:

relations = request.POST.getlist('relations')

How do I handle it all? Currently I'm doing it with <input type="radio"..., but of course it couldn't work if it has same name in once form. But if I use: <input type="checkbox"..., the answers can be check more than 1 in once question...

Maybe like this:

<input type="radio" name="answer-{{ question.id }}">

How can I get it all in the view?

Solved:

In my test:

{% for question in questions %}
    <input type="hidden" name="question" value="{{ question.id }}/>

    {% for answer in question.get_answers %}
        <input type="radio" name="answer-{{ question.id }}" value={{ answer.score }}>
    {% endfor %}
{% endfor %}

views.py

questions = request.POST.getlist('question')
answers = [request.POST['answer-{}'.format(q)] for q in questions]

And the results of it:

['20', '19', '16', '13', '11', '10', '9', '8', '1']
['5', '2', '3', '4', '1', '4', '4', '2', '2']

解决方案

If I understood you right you need to implement multiple choice? Then you can do in your template this:

{% for answer in answers %}
    <input type="checkbox" name="answer" id="answer{{ forloop.counter }}" value="{{ answer.id }}">
{% endif %}

Andi in view:

answer = request.POST.getlist('answer')
for el in answer:
    pass

这篇关于Django具有相同名称的多个输入字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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