我正在尝试获取名称和姓氏值并将其打印到HTML。这是我的代码:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from emailai.models import Vartotojas
from renginiai.forms import VartotojasForm
def name(request):
if request.method == 'GET':
form = VartotojasForm(request.GET)
name = form.data['name']
surname = form.data['surname']
return render(request, 'vartotojas-result.html', {'form': form, 'name': names, 'surname': surname })
else:
form = VartotojasForm()
return render(request, 'vartotojas-form.html', {'form': form})
Vartotojas-form.html
<html>
<head>
<title>Name</title>
</head>
<body>
<h1>Name</h1>
<form action="sumbit" method="get">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</body>
我在/ name /得到KeyError。我的错误在哪里?
答案 0 :(得分:1)
试试这个:
def name(request):
if request.method == 'POST':
form = VartotojasForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
surname = form.cleaned_data['surname']
return render(request, 'vartotojas-result.html', {'form': form, 'name': name, 'surname': surname })
else:
form = VartotojasForm()
return render(request, 'vartotojas-form.html', {'form': form})
同样在渲染参数中,您的names
变量未定义:
{'form': form, 'name': names, 'surname': surname }
将其更改为name
:
{'form': form, 'name': name, 'surname': surname }
并将您的Vartotojas-form.html
表单更改为:
<html>
<head>
<title>Name</title>
</head>
<body>
<h1>Name</h1>
<form action="sumbit" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
</body>
答案 1 :(得分:0)
确保您的模板在输入标记中使用name参数
<input type="text" name="surname" value="">
<input type="text" name="name" value="">
并且Django表单中的字段与html表单中的字段匹配