Django如何验证POST参数 [英] Django how to validate POST Parameters
问题描述
有没有可以使用的django函数?
例如:
code> if request.method =='POST':
print request.POST.get('user_comment')
如何检查POST参数是否包含系统的非危险字符串?像
request.POST.get('user_comment')is_valid()
谢谢。
code> POST 数据是安全的,有正确的类型等你可以使用django中的表单。例如,如果您期望3个必需参数,一个字符串和2个整数,则可以从django导入表单创建表单:
class MyValidationForm(forms.Form):
first = forms.CharField()
second = forms.IntegerField()
third = forms.IntegerField()
并在视图中使用它:
if request.method =='POST':
form = MyValidationForm(request.POST,request.FILES)
如果不是form.is_valid():
#print some error here
else:
#do whatever you like
For过滤如果字符串不包含危险的东西,则没有一般的解决方案。数据库,XSS等都有不同的威胁,所以没有办法过滤全部。
I pass some parameters to django by a POST request. How can I validate if a parameter is an integer, a String and also that there is no unsecure stuff like code injection inside? Is there a django function I can use?
For example:
if request.method == 'POST':
print request.POST.get('user_comment')
How can I check if the POST parameter contains a non dangerous String for my system? Something like
request.POST.get('user_comment').is_valid()
Thanks.
For checking if POST
data is safe, have correct type etc you can use forms in django. For example if you're expecting 3 required parameters, one string and 2 integers, you can create form:
from django import forms
class MyValidationForm(forms.Form):
first = forms.CharField()
second = forms.IntegerField()
third = forms.IntegerField()
And using it in view:
if request.method == 'POST':
form = MyValidationForm(request.POST, request.FILES)
if not form.is_valid():
# print some error here
else:
# do whatever you like
For filtering if string doesn't contain something dangerous, there is no general solution. There are different threats for databases, XSS etc so there is no way to filter it all.
这篇关于Django如何验证POST参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!