Reputation: 45
I have a very simple django app that passes some form input into an AJAX call. The whole thing works great as is, with uncleaned data, but I'd like to be sure I'm passing only [a-zA-Z], no special chars, and no ints. Is it best to handle this with a custom validator on the form/model field? OR, is it better to clean it in the view tied to the AJAX request?
Here is an incomplete snippet of my AJAX call and related view.
$.ajax({
url : "/create_post/",
type : "POST",
data : {
first_name : $('#id_first_name').val(),
last_name : $('#id_last_name').val(),
department : $('#id_department').val()
},
The relevant part of the view:
def create_post(request):
if request.method == 'POST':
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
department = request.POST.get('department')
...
results = search(first_name, last_name, department)
Upvotes: 2
Views: 1001
Reputation: 23346
Firstly, you definitely want to do it on the server. Validation in the javascript is advisable for usability reasons, but it is not a replacement for server side validation.
Handling validation of data from JSON requests is the same as an any other view: use a django form. Setup the fields as usual, load the data in and call is_valid
.
So, something like this:
class UserForm(Form):
first_name = forms.RegexField(regex=r'$[a-zA-Z]^')
# ...etc
def create_post(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
return search(form.cleaned_data['first_name'], ...)
else:
# some sort of error response
Upvotes: 3