Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.94 KB | None | 0 0
  1. #### forms.py #####
  2.  
  3. #This form is a one-field form with the sole purpose of validating the email.
  4. class EmailValidationForm (forms.Form):
  5.  
  6. reg_email = forms.EmailField()
  7.  
  8. def __init__(self, *args, **kwargs):
  9. super(EmailValidationForm, self).__init__(*args, **kwargs)
  10. self.fields['reg_email'].required = True
  11.  
  12. def clean(self):
  13. existing_user = User.objects.filter(email=self.cleaned_data['reg_email']).first()
  14. if existing_user != None:
  15. raise forms.ValidationError("This e-mail is already in use.")
  16.  
  17. return self.cleaned_data
  18.  
  19.  
  20. #### views.py #####
  21.  
  22. #The page with the form
  23. def show_form (request, template="my_form.html"):
  24.  
  25. form = EmailValidationForm ()
  26.  
  27. return render(request, template, locals())
  28.  
  29.  
  30. #The view to validate the e-mail
  31. def validate_user_email (request):
  32. form = EmailValidationForm(data=request.POST)
  33.  
  34. if form.is_valid():
  35. return JsonResponse({
  36. 'status': 'ok',
  37. 'html': '',
  38. })
  39.  
  40. else:
  41. return JsonResponse({
  42. 'status': 'errors',
  43. 'html': render_to_string('ajax_form_errors.html', locals())
  44. })
  45.  
  46.  
  47. #### HTML my_form.html #####
  48.  
  49. <form class="form" method="POST" action="#" id="email_validation_form">
  50. <label>{{ form.reg_email.label }}</label>
  51. {{ form.reg_email }}
  52.  
  53. <div id="form_errors_wrapper"></div>
  54. </form>
  55.  
  56. #### HTML - ajax_form_errors.html ####
  57. {% if form.errors %}
  58. {% for field in form %}
  59. {% for error in field.errors %}
  60. <div class="alert alert-danger">
  61. <strong>{{ field.label }} - {{ error|escape }}</strong>
  62. </div>
  63. {% endfor %}
  64. {% endfor %}
  65. {% for error in form.non_field_errors %}
  66. <div class="alert alert-danger">
  67. <strong>{{ error|escape }}</strong>
  68. </div>
  69. {% endfor %}
  70. {% endif %}
  71.  
  72.  
  73.  
  74.  
  75. #### Javascript #####
  76.  
  77. <script>
  78. function validate_user_email () {
  79.  
  80. $.ajax({
  81. async: true,
  82. type: "POST",
  83. beforeSend: function (request)
  84. {
  85. request.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); //this adds the CSRF token in the ajax call
  86. },
  87. url: "{% url 'validate_user_email' %}",
  88. data: $('#email_validation_form').serialize(),
  89. dataType: 'json',
  90. contentType: "application/x-www-form-urlencoded;charset=UTF-8",
  91. success: function(data){
  92. //No form errors.. all good
  93. if (data.status == "ok") {
  94. $('#form_errors_wrapper').html('');
  95.  
  96. //The e-mail is invalid.. show the errors.
  97. } else {
  98. $('#form_errors_wrapper').html(data.html);
  99. }
  100. },
  101. complete: function () {
  102. },
  103. error: function(XMLHttpRequest, textStatus, errorThrown) {
  104. alert('server error');
  105. }
  106. });
  107. }
  108.  
  109.  
  110. //Since a simple keyup listener will trigger the validation at every keystroke, you can do something like this to only check after 300ms of the last keystroke.
  111.  
  112. var search_timeout = undefined;
  113. $(function(){
  114. $('#id_reg_email').keyup(function() {
  115. if(search_timeout != undefined) {
  116. clearTimeout(search_timeout);
  117. }
  118. search_timeout = setTimeout(function() {
  119. search_timeout = undefined;
  120. validate_user_email();
  121. }, 300);
  122. });
  123. });
  124.  
  125. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement