Saturday, June 1, 2013

Cleaning and Validating POST request data in Django

Users are evil. They send us bad data all the time. Sometimes they try to delete our database by naming their children strangely. Sometimes they send us their phone number where an email address was expected. They want our servers to crash and bad things to happen. We must be paranoid when dealing with their data.

When using Django forms, we get the help of cleaners and validators to keep the bad guys out. But what to do when we need to do this new fangled API stuff? User data coming directly into our views! Oh the horrors! Users must be getting wet eyes from all the evil laughter.

But in Django, we like to keep thing DRY. And so here is what we do. We can use a Form only for the validation and cleaning of data. Nothing mandates that we have to use the generated HTML for displaying the form.

Let us say, we have a AJAX request bringing in data from a registration form. So we create a Form as follow:

class AJAXRegisterForm(forms.Form):
  '''Form for validating the AJAX request'''
  username = forms.CharField(max_length=64)
  email = forms.CharField(max_length=32)
  evil_plan = forms.CharField(max_length=255)

This is how we proceed in the views:
def user_register(request):
  if request.method == 'POST': 
    regform = AJAXRegisterForm(request.POST)
      if regform.is_valid():
        # The cleaned form data is available here in 
        # form.cleaned_data dictionary
        # We can now safely add the user to our spam list
        # If required, we can add custom validators to the form
      else:
        # Send back an appropriate insult telling them 
        # that their evil plan failed
        ret = {'warning': 'Do not mess with Django Warriors'}
        HttpResponseServerError(json.dumps(ret), 
                                mimetype="application/json")
And thus keep the evil users at bay.

No comments:

Post a Comment