首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试查看网页源码时出现Django错误

尝试查看网页源码时出现Django错误
EN

Stack Overflow用户
提问于 2015-02-04 11:43:49
回答 2查看 145关注 0票数 0

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

代码语言:javascript
复制
<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>

我使用隐藏字段来存储值,以保持会话无状态(分配点)。我正在尝试调试我的隐藏字段,然而,在我启动我的应用程序并触发下面的第一个if语句后,我不再能够查看网页源代码(通过右键单击网页并单击"view source")。当我尝试这样做时,它首先显示“文档过期”,但它允许我再次尝试请求。当我再试一次时,下面的html显示为源代码。

代码语言:javascript
复制
    <!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>MultiValueDictKeyError at /press</title>
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; }
    h2 { margin-bottom:.8em; }
    h2 span { font-size:80%; color:#666; font-weight:normal; }
    h3 { margin:1em 0 .5em 0; }
    h4 { margin:0 0 .5em 0; font-weight: normal; }
    code, pre { font-size: 100%; white-space: pre-wrap; }
    table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
    tbody td, tbody th { vertical-align:top; padding:2px 3px; }
    thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }
    tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
    table.vars { margin:5px 0 2px 40px; }
    table.vars td, table.req td { font-family:monospace; }
    table td.code { width:100%; }
    table td.code pre { overflow:hidden; }
    table.source th { color:#666; }
    table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
    ul.traceback { list-style-type:none; color: #222; }
    ul.traceback li.frame { padding-bottom:1em; color:#666; }
    ul.traceback li.user { background-color:#e0e0e0; color:#000 }
    div.context { padding:10px 0; overflow:hidden; }
    div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
    div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; }
    div.context ol li pre { display:inline; }
    div.context ol.context-line li { color:#505050; background-color:#dfdfdf; }
    div.context ol.context-line li span { position:absolute; right:32px; }
    .user div.context ol.context-line li { background-color:#bbb; color:#000; }
    .user div.context ol li { color:#666; }
    div.commands { margin-left: 40px; }
    div.commands a { color:#555; text-decoration:none; }
    .user div.commands a { color: black; }
    #summary { background: #ffc; }
    #summary h2 { font-weight: normal; color: #666; }
    #explanation { background:#eee; }
    #template, #template-not-exist { background:#f6f6f6; }
    #template-not-exist ul { margin: 0 0 0 20px; }
    #unicode-hint { background:#eee; }
    #traceback { background:#eee; }
    #requestinfo { background:#f6f6f6; padding-left:120px; }
    #summary table { border:none; background:transparent; }
    #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
    #requestinfo h3 { margin-bottom:-1em; }
    .error { background: #ffc; }
    .specific { color:#cc3300; font-weight:bold; }
    h2 span.commands { font-size:.7em;}
    span.commands a:link {color:#5E5694;}
    pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; }
  </style>

  <script type="text/javascript">
  //<!--
    function getElementsByClassName(oElm, strTagName, strClassName){
        // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com
        var arrElements = (strTagName == "*" && document.all)? document.all :
        oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        strClassName = strClassName.replace(/\-/g, "\-");
        var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
        var oElement;
        for(var i=0; i<arrElements.length; i++){
            oElement = arrElements[i];
            if(oRegExp.test(oElement.className)){
                arrReturnElements.push(oElement);
            }
        }
        return (arrReturnElements)
    }
    function hideAll(elems) {
      for (var e = 0; e < elems.length; e++) {
        elems[e].style.display = 'none';
      }
    }
    window.onload = function() {
      hideAll(getElementsByClassName(document, 'table', 'vars'));
      hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
      hideAll(getElementsByClassName(document, 'ol', 'post-context'));
      hideAll(getElementsByClassName(document, 'div', 'pastebin'));
    }
    function toggle() {
      for (var i = 0; i < arguments.length; i++) {
        var e = document.getElementById(arguments[i]);
        if (e) {
          e.style.display = e.style.display == 'none' ? 'block': 'none';
        }
      }
      return false;
    }
    function varToggle(link, id) {
      toggle('v' + id);
      var s = link.getElementsByTagName('span')[0];
      var uarr = String.fromCharCode(0x25b6);
      var darr = String.fromCharCode(0x25bc);
      s.innerHTML = s.innerHTML == uarr ? darr : uarr;
      return false;
    }
function switchPastebinFriendly(link) {
  s1 = "Switch to copy-and-paste view";
  s2 = "Switch back to interactive view";
  link.innerHTML = link.innerHTML == s1 ? s2: s1;
  toggle('browserTraceback', 'pastebinTraceback');
  return false;
}
//-->

除此之外,我不太确定发生了什么。我试着用谷歌搜索这个问题,但我对这种情况的缺乏理解使我无法找到任何有用的东西。希望有人能指出我做得不对的地方。

--编辑--这是我的views.py文件。

代码语言:javascript
复制
from django.shortcuts import render
from django.http import HttpResponse


# Create your views here.
def home_page(request):
    index = 'calculator/calculator.html'
    return render(request,index,{})

def press(request):
    context = {}
    operators = ['plus','minus','divide','multiply']
    index = 'calculator/calculator.html'

    ## Discerns from a number and an operator press
    if 'val' in request.POST and is_int(request.POST['val']):
        if request.POST['output'] == '0':
            context['output'] = request.POST['val']
            context['buttVal'] = request.POST['val']
            context['currVal'] = request.POST['val']
        elif request.POST['currVal'] == '0':
            context['output'] = request.POST['val']
            context['buttVal'] = request.POST['val']
            context['currVal'] = request.POST['val']
        else:
            newOutput = request.POST['output'] + request.POST['val']
            context['buttVal'] = request.POST['val']
            context['currVal'] = newOutput
            context['output'] = newOutput

        context['math'] = request.POST['math']
        context['prevVal'] = request.POST['prevVal']

    elif request.POST['val'] == 'clear':
        context['output'] = 0
        context['buttVal'] = 0
        context['currVal'] = 0
        context['prevVal'] = 0
        context['math'] = ''
    elif request.POST['val'] in operators:
        print request.POST
        if request.POST['math'] != '':
            print "poop"
            if request.POST['math'] == 'plus':
                result = int(request.POST['currVal']) + int(request.POST['prevVal'])
                context['prevVal'] = result
                context['output'] = result
            if request.POST['math'] == 'minus':
                result = int(request.POST['currVal']) - int(request.POST['prevVal'])
                context['prevVal'] = result
                context['output'] = result
            if request.POST['math'] == 'multiply':
                result = int(request.POST['currVal']) * int(request.POST['prevVal'])
                context['prevVal'] = result
                context['output'] = result
            if request.POST['math'] == 'divide':
                result = int(request.POST['currVal']) / int(request.POST['prevVal'])
                context['prevVal'] = result
                context['output'] = result
            if request.POST['val'] == 'equal':
                pass
        else:
            context['prevVal'] = request.POST['currVal']
            #context['math'] = request.POST['val']
            context['output'] = request.POST['output']
        context['math'] = request.POST['val']
        context['buttVal'] = request.POST['buttVal']
        context['currVal'] = 0
    else:
        context['output'] = request.POST['output']
        context['buttVal'] = request.POST['buttVal']
        context['math'] = request.POST['math']
        context['prevVal'] = request.POST['prevVal']

     ## Submits POST
    return render(request, index, context)

## Helper functions
def is_int(string):
    try: 
        int(string)
        return True
    except ValueError:
        return False
EN

回答 2

Stack Overflow用户

发布于 2015-02-04 12:30:35

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

代码语言:javascript
复制
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']

您没有检查valoutputbuttValprevValmath是否在request.POST中。

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

代码语言:javascript
复制
request.POST.get('val')

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

添加print request.POSTpress()视图的最开始部分,查看"view source“请求中POST数据的内容。

票数 0
EN

Stack Overflow用户

发布于 2015-02-04 12:35:15

发生这种情况的原因是,当您在浏览器中查看页面的源代码时,会发出另一个请求;但这是一个GET请求。

因此,您的POST字典没有这些键,从而导致了异常。

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

代码语言:javascript
复制
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})

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28313129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档