Django detail vi中的多值DictKeyError

2024-04-16 18:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在django做一个应用程序。这是我的索引.html第页。你知道吗

<!DOCTYPE html>

<html>
<head>
    <title>The index page</title>
</head>
<body>
    <h1>Choose the name of student</h1>
    <form action= "{% url 'detail' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
            <select name="namedrop">
                {% for name in student_list %}
                <option>{{name.stuname}}</option>
                {% endfor %}

            </select>

    <input type="submit" name="submit">
    </form>
</body>
</html>

这是我的学生信息/网址.py你知道吗

from django.conf.urls import url
from . import views
from .models import student

urlpatterns= [
    url(r'^$',views.index ,name='index'),
    url(r'^detail/$',views.detail ,name='detail'),

]

这就是视图.py你知道吗

from .models import student
from django.http import Http404
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse


def index(request):
    student_list=student.objects.all()
    template = loader.get_template('studinfo/index.html')
    context= { 'student_list' : student_list, }
    return HttpResponse(template.render(context, request))


def detail(request):
    if request.method=='POST':
        name=request.GET['namedrop']
        return render(request, 'detail.html', {'name':name})

现在它提出了一个错误 /studinfo/detail处的多值dictkeyerror/ “'namedrop'” 我不知道为什么…如果有人知道就告诉我。你知道吗


Tags: djangonamefromimportformurlindexrequest
2条回答

一个非常简单的错误是,您试图获取请求数据,而您正在接收post数据。你知道吗

改变这个

name=request.GET['namedrop']

为了这个

name=request.POST['namedrop']

如果request.GET是一个拼写错误,而您的意思是request.POST['namedrop'],那么您应该做两件事。你知道吗

在您的视图中尝试以下操作:

name=request.POST.get('namedrop', '')   # give it a default value

这将确保即使未发送namedrop也不会有任何错误。您可以提供一个默认值。你知道吗

然后,在你的索引.html,您应该给option标记一个值:

<option value={{name.stuname}}>{{name.stuname}}</option>

没有它,什么也看不见。你知道吗

希望有帮助!你知道吗

相关问题 更多 >