Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to validate POST Parameters

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.

like image 267
John Smithv1 Avatar asked Nov 20 '15 14:11

John Smithv1


People also ask

How does Django validate data in serializer?

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.

How does Django validate data?

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.

How do I display validation error in Django?

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.


1 Answers

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.

like image 99
GwynBleidD Avatar answered Oct 02 '22 21:10

GwynBleidD