【发布时间】:2011-06-10 00:38:28
【问题描述】:
如何从 django 框架中的表单字段中获取值?我想在视图中执行此操作,而不是在模板中...
【问题讨论】:
如何从 django 框架中的表单字段中获取值?我想在视图中执行此操作,而不是在模板中...
【问题讨论】:
Using a form in a view 解释得差不多了。
在视图中处理表单的标准模式如下所示:
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,
})
【讨论】:
class ContactForm(forms.Form): my_form_field_name = forms.CharField()
任你选:
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
注意:该字段一旦可用就会被访问。
【讨论】:
form['my_field'].value() 用于在 POST 请求中访问表单值。有些日子:|
您可以在验证数据后执行此操作。
if myform.is_valid():
data = myform.cleaned_data
field = data['field']
另外,阅读 django 文档。他们是完美的。
【讨论】:
我使用 django 1.7+ 和 python 2.7+,上面的解决方案不起作用。 表单中的输入值可以使用 POST 获取,如下所示(使用与上面相同的表单):
if form.is_valid():
data = request.POST.get('my_form_field_name')
print data
希望这会有所帮助。
【讨论】:
要从发送 post 请求的表单中检索数据,您可以这样做
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")
【讨论】:
如果你使用的是 django 3.1 及以上版本,这很容易
def login_view(request):
if(request.POST):
yourForm= YourForm(request.POST)
itemValue = yourForm['your_filed_name'].value()
# Check if you get the value
return HttpResponse(itemValue )
else:
return render(request, "base.html")
【讨论】:
Cleaned_data 将提交的表单转换为 dict,其中 keys 表示表单中使用的属性名称,value 是用户提交的响应。访问我们编写的视图中的特定值:
formname.cleaned_data['fieldname']
【讨论】: