我试图从django中获取一个帖子的值,但它传递一个空字段`def PersonEmail(request):
我试图从django中获取一个帖子的值,但它传递一个空字段`def PersonEmail(request):
if request.method == "POST":
form1 = PersonForm(request.POST, prefix="form1")
form2 = EmailForm(request.POST, prefix="form2")
name = form2['email'].value
return HttpResponse(name)
else:
form1 = PersonForm()
form2 = EmailForm()
return render(request, 'CreatePersonEmail.html', locals())`
但当我把它们分开时,
Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):
if request.method == "POST":
# form1 = PersonForm(request.POST, prefix="form1")
form2 = EmailForm(request.POST, prefix="form2")
name = form2['email'].value
return HttpResponse(name)
else:
form1 = PersonForm()
form2 = EmailForm()
return render(request, 'CreatePersonEmail.html', locals())`
它给了我该领域的价值。
为什么呢?以及如何使它获取两个表单字段的值?
答案 0 :(得分:1)
基本上,你做错了。
首先,您需要检查表单是否有效。用户可以输入任何废话,你不想让他们这样做:
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
# Now you can access the fields:
name = form.cleaned_data['name']
如果表单无效,只需将其传回render()
即可显示错误。
另外,不要这样做:
return render(request, 'CreatePersonEmail.html', locals())`
正确构建您的上下文字典,不要使用locals()
,这会让您的上下文受到污染。
所以完整视图可能看起来像这样(取自django docs并稍作改动:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
name = form.cleaned_data['name']
return render(request, 'some_page.html', {'name': name})
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
答案 1 :(得分:0)
您需要在实例化表单时使用前缀;在GET和POST上都有。
此外,您可以从表单的cleaned_data
字典中获取值,而不是来自字段。