Python 如何从 django 框架中的表单字段中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4706255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value from form field in django framework?
提问by kspacja
How do I get values from form fields in the django framework? I want to do this in views, not in templates...
如何从 django 框架中的表单字段中获取值?我想在视图中执行此操作,而不是在模板中...
采纳答案by miku
Using a form in a viewpretty much explains it.
在视图中使用表单几乎可以解释它。
The standard pattern for processing a form in a view looks like this:
在视图中处理表单的标准模式如下所示:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
print form.cleaned_data['my_form_field_name']
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
回答by ikostia
You can do this after you validate your data.
您可以在验证数据后执行此操作。
if myform.is_valid():
data = myform.cleaned_data
field = data['field']
Also, read the django docs. They are perfect.
另外,请阅读 django 文档。他们是完美的。
回答by zhihong
I use django 1.7+ and python 2.7+, the solution above dose not work. And the input value in the form can be got use POST as below (use the same form above):
我使用 django 1.7+ 和 python 2.7+,上面的解决方案不起作用。并且表单中的输入值可以使用 POST 获取,如下所示(使用与上面相同的表单):
if form.is_valid():
data = request.POST.get('my_form_field_name')
print data
Hope this helps.
希望这可以帮助。
回答by laffuste
Take your pick:
随你挑:
def my_view(request):
if request.method == 'POST':
print request.POST.get('my_field')
form = MyForm(request.POST)
print form['my_field'].value()
print form.data['my_field']
if form.is_valid():
print form.cleaned_data['my_field']
print form.instance.my_field
form.save()
print form.instance.id # now this one can access id/pk
Note: the field is accessed as soon as it's available.
注意:该字段一可用就被访问。
回答by ChandyShot
To retrieve data from form which send post request you can do it like this
要从发送发布请求的表单中检索数据,您可以这样做
def login_view(request):
if(request.POST):
login_data = request.POST.dict()
username = login_data.get("username")
password = login_data.get("password")
user_type = login_data.get("user_type")
print(user_type, username, password)
return HttpResponse("This is a post request")
else:
return render(request, "base.html")

