Python 当我试图查看网页源时出现Django错误

Python 当我试图查看网页源时出现Django错误,python,html,django,post,hidden-field,Python,Html,Django,Post,Hidden Field,我正在使用Django为一个类创建一个web应用程序。下面的HTML片段是我认为可能导致我的问题的原因 <form action="press" method="POST"> <table> <tr> <td colspan="4"> {% if output %} <input id="output" name="output" type="text" value="{{output}}" rea

我正在使用Django为一个类创建一个web应用程序。下面的HTML片段是我认为可能导致我的问题的原因

<form action="press" method="POST">
<table>
  <tr>
      <td colspan="4">
      {% if output %}
        <input id="output" name="output" type="text" value="{{output}}" readonly>
      {% else %}
        <input id="output_hidden" name="output" type="text" value="0" readonly>
      {% endif %}
      <input type="hidden" name="buttVal" value="{{buttVal}}">
      <input type="hidden" name="currVal" value="{{currVal}}">
      <input type="hidden" name="prevVal" value="{{prevVal}}">
      <input type="hidden" name="math" value="{{math}}">
      {% csrf_token %}
      </td>

您正在尝试访问request.POST中不存在的参数。例如:

elif request.POST['val'] == 'clear':
    ...
elif request.POST['val'] in operators:
    ...
else:
    context['output'] = request.POST['output']
    context['buttVal'] = request.POST['buttVal']
    context['math'] = request.POST['math']
    context['prevVal'] = request.POST['prevVal']
您没有检查request.POST中是否有val、output、buttVal、prevVal和math

要安全地从request.POST获取值,请使用get方法:

此表达式将返回request.POST的val参数,如果该参数不存在,则返回None


添加print request.POST和press view的最开始部分,以查看view source request中POST数据的内容。

这是因为当您在浏览器中查看页面的源时,会发出另一个请求;但这是一个GET请求

因此,您的PostDictionary没有这些键,从而导致异常

解决这个问题最简单的方法是使用表单

class MyForm(forms.Form):
    output = forms.TextField()
    # .. your other fields here

def press(request):
    form = MyForm(request.POST or None)
    if form.is_valid():
        # do stuff
        return redirect('/home')
    return render(request, 'template.html', {'form': form})

您可以阅读有关表单的更多信息,包括如何隐藏字段和在中传递初始值。

错误在python代码中的某个地方。请显示视图的来源。此外,浏览器中堆栈跟踪的最后一部分应指向发生错误的实际行。@catavaran,这样我的web应用程序就可以正常运行,而不会产生任何错误。没有传统的django错误指向我与它交互时生成的行。这是让我困惑的部分原因。我能判断出问题的唯一原因是当我试图手动查看网页的源代码时。您所指的视图的来源是什么?网页是源代码还是views.py代码?如果它是源代码,那么它就是上面的第二个大代码段。我没有复制整个东西,因为它相当大。第一个代码片段中的html代码不能生成keyrerror。因此,错误出现在views.py或从views.py调用的代码中。您必须显示映射到此url的view函数的代码。没问题,我想在添加之前确保这是您希望看到的。这很难看,只是一个预先声明。
elif request.POST['val'] == 'clear':
    ...
elif request.POST['val'] in operators:
    ...
else:
    context['output'] = request.POST['output']
    context['buttVal'] = request.POST['buttVal']
    context['math'] = request.POST['math']
    context['prevVal'] = request.POST['prevVal']
request.POST.get('val')
class MyForm(forms.Form):
    output = forms.TextField()
    # .. your other fields here

def press(request):
    form = MyForm(request.POST or None)
    if form.is_valid():
        # do stuff
        return redirect('/home')
    return render(request, 'template.html', {'form': form})