ajax form validation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@ajax_request
def check_avail(request):
checkable_fields = {
'username': forms.RegexField(regex=r'^\w+$', max_length=30),
'email': forms.EmailField(),
}
try:
field = str(request.REQUEST.get('field', ''))
assert field in checkable_fields, ("field must be one of %s" % checkable_field.keys())
value = request.REQUEST.get('value', '')
try:
User.objects.get(**{field: value})
except User.DoesNotExist:
try:
checkable_fields[field].clean(value)
except forms.ValidationError, e:
return {
'success': True,
'result': False,
'message': unicode(e.messages),
}
else:
return {'success': True, 'result': True, 'message': ''}
else:
return {'success': True, 'result': False, 'message': _('This value is already taken')}
except Exception, e:
return {'success': False, 'message': unicode(e.message)}