簡體   English   中英

Django-通過 <select>從一個視圖到另一個視圖形成POST數據

[英]Django - Pass a <select> form POST data from one view to another

我試圖將我從表單收集的數據傳遞到另一頁上。 我是Django的初學者,但仍然不了解POST和GET。

過去幾天,我一直在努力解決此問題,但我一直在圈子里奔波。 我假設這是一個相當簡單的問題,但我只是不知道發生了什么。

我希望在選擇興趣視圖中單擊“提交”后,會將選擇的興趣發送到另一個名為“選擇學科”的視圖。 我希望能夠在我的select_discipline視圖中使用所選興趣。

views.py

@login_required
def select_interest(request):
    context = RequestContext(request)
    interests = Interest.objects.order_by('name')

    return render_to_response('selectinterest.html', {'interests': interests, 'disciplines': disciplines }, context )

@login_required
def select_discipline(request):


    interest = request.POST.get('interest-select')
    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 )

selectinterest.html

<div class = "container">
  <h1>Change Primary Interest</h1>

  <form action="{% url 'myapp:select_discipline' %}" method="POST" id="interest-select">
    {% csrf_token %}
    <select title="interest-select" id="usrInterest">
      <option disabled selected> -- select an option -- </option>
      {% for i in interests %}
      <option name = "interest" value={{i.id}}>{{i.name}}</option>
      {% endfor %}

    </select> -->
    <input type="submit" value="Load Disciplines"/>
  </form>
</div>

注意:我認為問題在於您沒有在select標簽中定義'name'屬性。 您應該在標簽select中使用屬性“ 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
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM