Django - 将<select>表单POST数据从一个视图传递到另一个视图

时间:2015-06-23 23:47:29

标签: python django

我试图将从表单收集的数据传递到另一个页面。我是Django的初学者,仍然不懂POST和GET。 过去几天我一直试图解决这个问题,但我一直在圈子里跑。我假设这是一个相当简单的问题,但我只是不知道发生了什么。 我希望在我选择的兴趣视图中,一旦我点击提交,就会将所选兴趣发送到另一个名为select discipline的视图。我希望能够在select_discipline视图中使用所选择的兴趣。 views.py @要求登录 def select_interest(request):     context = RequestContext(request)     兴趣= Interest.objects.order_by('name')     return render_to_response('selectinterest.html',{'interest':interest,'disciplines':disciplines},context) @要求登录 def select_discipline(request):     interest = request.POST.get('interest-select')     context = RequestContext(request)     兴趣= Interest.objects.order_by('name')     disciplines = Discipline.objects.filter(parentInterest = interest)     return render('selectdiscipline.html',{'interest':interest,'interest':interest,'disciplines':disciplines},context) selectinterest.html &lt; div class =“container”&gt;   &lt; h1&gt;更改主要兴趣&lt; / h1&gt;   &lt; form action =“{%url'myapp:select_discipline'%}”method =“POST”id =“interest-select”&gt;     {%csrf_token%}     &lt; select title =“interest-select”id =“usrInterest”&gt;       &lt;选择已禁用选项&gt; - 选择一个选项 - &lt; / option&gt;       {%for i in interest%}       &lt; option name =“interest”value = {{i.id}}&gt; {{i.name}}&lt; / option&gt;       {%endfor%}     &LT; /选择&GT; - &GT;     &lt; input type =“submit”value =“Load Disciplines”/&gt;   &LT; /形式&GT; &LT; / DIV&GT;

1 个答案:

答案 0 :(得分:0)

  

注意:我认为问题是你没有在select标签中定义'name'属性。你应该在标签选择中使用属性'name',因为,这是使用字典POST的名称。另外,我建议使用django-crispy-forms

selectinterest.html

<div class="container">
  <h1>Change Primary Interest</h1>
  <form action="{% url 'myapp:select_discipline' %}" method="POST" id="interest-select">
    {% csrf_token %}
    <select id="id_interest" name="interest">
      <option disabled selected> -- select an option -- </option>
      {% for i in interests %}
      <option value={{i.id}}>{{i.name}}</option>
      {% endfor %}
    </select>
    <input type="submit" value="Load Disciplines"/>
  </form>
</div> 

views.py

@login_required
def select_discipline(request):
    if request.method == 'POST':
        interest = request.POST.get('interest')
        context = RequestContext(request)
        interests = Interest.objects.order_by('name')
        disciplines = Discipline.objects.filter(parentInterest=interest)

        return render(
            'selectdiscipline.html',
            {
                'interest': interest,
                'interests': interests,
                'disciplines': disciplines
            },
            context
        )