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.
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting a requires_context = True attribute on the validator. The __call__ method will then be called with the serializer_field or serializer as an additional argument.
Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With