Created
December 20, 2017 09:03
-
-
Save 63phc/95da6c7441b99271b1e644f3ae7353d7 to your computer and use it in GitHub Desktop.
ajaxResponseMixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AjaxResponseMixin(object): | |
message_success = '' | |
message_error = '' | |
message_recaptcha = 'Не забывайте про капчу' | |
def form_invalid(self, form): | |
response = super(AjaxResponseMixin, self).form_invalid(form) | |
if self.request.is_ajax(): | |
data = { | |
'errors': form.errors, | |
'status': 400, | |
'message_error': self.message_error | |
} | |
errors = json.dumps(data, ensure_ascii=False) | |
return JsonResponse(errors, status=400, safe=False) | |
else: | |
return response | |
def form_valid(self, form): | |
recaptcha_response = self.request.POST.get('g-recaptcha-response') | |
data_request_captcha = { | |
'secret': GOOGLE_RECAPTCHA_SECRET_KEY, | |
'response': recaptcha_response | |
} | |
data_response_form = { | |
'pk': self.object.pk, | |
'message_success': self.message_success, | |
'status': 200 | |
} | |
request_captcha = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data_request_captcha, | |
verify=False) | |
response_captcha = request_captcha.json() | |
if response_captcha['success']: | |
form.save(commit=True) | |
data_response_form.update({ | |
'message_success': self.message_success, | |
'status': 200, | |
}) | |
else: | |
data_response_form.update({ | |
'message_success': self.message_recaptcha, | |
'status': 202, | |
}) | |
response = super(AjaxResponseMixin, self).form_valid(form) | |
if self.request.is_ajax(): | |
data_response = json.dumps(data_response_form, ensure_ascii=False) | |
return JsonResponse(data_response, status=200, safe=False) | |
else: | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment