在request.session中获取KeyError

时间:2018-05-14 18:42:44

标签: python django session django-forms

这是我在Django中使用会话的代码。一切似乎都很好,但在/ addfixeddeposit /

获得KeyError
  

views.py

def anotherpage(request, account_number):
    form = FixedDepositForm()
    context = {'form' : form}
    request.session['account_number'] = account_number
    return render(request, 'bankmanagement/another_page.html', context)

def addfixeddeposit(request):
    if request.method == "POST":
        var = request.session['account_number']
        print(var)
        form = FixedDepositForm(request.POST)
        if form.is_valid:
            acc = Account.objects.get(pk = var)
            tenure = request.POST['tenure']
            rate = reuquest.POST['rate']
            new_fixed = FixedDeposit(account_number = acc, tenure = tenure, rate = rate)
            new_fixed.save()
            del request.session['account_number']
            return redirect('behome')
    return redirect('behome')

这是我使用会话值的html页面。然后在views.py

中的addfixeddeposit中
  

another_page.html

<form method="POST" action="{% url 'addfixeddeposit' %}">
                {% csrf_token %}
                <div class="form-field">
                    <table>
                        <tr>
                            <td><label for="accountnumfield" class="label--required">Account Number</label></td>
                            <td><label id="accountnumfield">{{ request.session['account_number'] }} </td>
                        </tr>
                        <tr>
                            <td><label for="tenure" class="label--required">Tenure</label></td>
                            <td><span id='tenure'>{{ form.tenure }}</span></td>
                        </tr>
                        <tr>
                            <td><label for="rate" class="label--required">Rate</label></td>
                            <td><span id='rate'>{{ form.rate }}</span></td>
                        </tr>
                    </table>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="a-btn--filled">Add</button>
                </div>
            </form>

1 个答案:

答案 0 :(得分:0)

如果您想将account_number从我的模板发送到视图,请使用查询字符串,使其更容易,就像在模板中一样:

<form method="POST" action="{% url 'addfixeddeposit' %}?account_number={{account_number}}">

然后在views.py做:

var = request.GET.get('account_number')