Python 如何在django框架中从表单字段中获取值?
如何从django框架中的表单字段中获取值?我想在视图中,而不是在模板中执行此操作…对此进行了解释 在视图中处理表单的标准模式如下所示:Python 如何在django框架中从表单字段中获取值?,python,django,Python,Django,如何从django框架中的表单字段中获取值?我想在视图中,而不是在模板中执行此操作…对此进行了解释 在视图中处理表单的标准模式如下所示: 您可以在验证数据后执行此操作 if myform.is_valid(): data = myform.cleaned_data field = data['field'] 另外,请阅读django文档。它们非常完美。我使用django 1.7+和python 2.7+,上面的解决方案不起作用。 表格中的输入值可通过如下POST获得(使用与上面相同的表
您可以在验证数据后执行此操作
if myform.is_valid():
data = myform.cleaned_data
field = data['field']
另外,请阅读django文档。它们非常完美。我使用django 1.7+和python 2.7+,上面的解决方案不起作用。 表格中的输入值可通过如下POST获得(使用与上面相同的表格): 希望这能有所帮助。选择:
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
注意:一旦该字段可用,就会立即访问它。要从发送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")
清理数据之前,只有request.POST与表单实例一起存储。清理是将POST数据与表单字段相关联的工作。在清理之前,您必须使用request.POST。如果设置了formField的初始值,是否可以获取其值?绑定表单的示例:
类ContactForm(forms.form):my_form_field_name=forms.CharField()
为什么模板可以运行{{form.name_of_field},当字段实际上是form.data或form.cleaned_data时?这个答案最好地总结了所有选项-访问原始帖子数据、未验证的表单字段和最终验证的表单字段。也许今天我只是在屏幕上看了太久,但我花了一个小时才找到这个非常简单的解决方案form['my_field'].value()
用于在POST请求时访问表单值。有些日子:|如果方法是“GET”,是否有办法将表单['your_field_name']'min'中属性的值设置为变量的值?我有一个表单,它有一个numberInputWidgets字段,但我正试图在views.py文件中设置它。当我打印yourForm.fields['form_field']时,我只能作为类访问该字段,而'min'似乎不可访问。以下是我在控制台中看到的:这是最好的答案,尤其是当您使用文档中的默认表单示例时
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")
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")