[英]POST doesnt work
我正在尝试从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())`
它给了我这个领域的价值。
为什么? 我怎样才能获得两个表单字段的值?
基本上,您做错了。
首先,您需要检查表格是否有效。 用户可以输入任何废话,但您不想让他们这样做:
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()
,因为它很hacky,会污染上下文。
因此,完整视图可能看起来像这样(取自django文档,并做了一些改动:
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})
实例化表单时,都需要使用前缀。 在GET和POST上都可以。
另外,您从表单的cleaned_data
dict中获取值,而不是从字段中获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.