Access the exception instance you are raising:
try:
if isDateValid(date) == false:
raise ValidationError('invalid date')
if usernameValid(user) == false:
raise ValidationError('invalid username')
except ValidationError as e:
data = json.dumps({'status': str(e)})
return HttpResponseBadRequest(data, content_type='application/json')
Well, the above will produce 'status': 'invalid date'. If you want to give the message 'enter a valid date' you have to see which message got passed:
except ValidationError as e:
msg = 'Enter a valid '
if str(e).endswith('date'):
msg += 'date'
else:
msg += 'username'
data = json.dumps({'status': msg})
return HttpResponseBadRequest(data, content_type='application/json')
Or even simpler:
except ValidationError as e:
msg = 'Enter a valid ' + str(e)[len('invalid '):]
data = json.dumps({'status': msg})
return HttpResponseBadRequest(data, content_type='application/json')
Personally you should ask yourself whether you could just use two different subclasses of ValidationError for the two different conditions.
You could have InvalidUsernameError and InvalidDateError and catch them separately. This would surely produce a much more robust solution (you aren't relying on the exact text passed to the raised exception), even though going too deep with class hierarchies isn't generally a good thing.
datavar directly in those if statements. And that would solve your message customization q.