Guest User

Untitled

a guest
Jul 29th, 2018
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. Django empty error messages
  2. def ajaxlogin(request):
  3. from forms import LoginForm
  4. form = LoginForm(request.POST)
  5. logged_in = False
  6. username = request.POST['username']
  7. password = request.POST['password']
  8. user = authenticate(username=username, password=password)
  9. if request.is_ajax() and user is not None:
  10. login(request, user)
  11. logged_in = True
  12. return HttpResponse(simplejson.dumps({'redirect' : 'true'}), content_type='application/json')
  13. else:
  14. return HttpResponse(simplejson.dumps({'errors': dict(form.errors.items())}), content_type='application/json')
  15.  
  16. from django import forms
  17. from django.contrib.auth.forms import AuthenticationForm
  18. from django.contrib.auth import authenticate
  19. from django.utils.translation import ugettext_lazy as _
  20.  
  21. class LoginForm(AuthenticationForm):
  22. username = forms.CharField(min_length=5, max_length=30,error_messages={'required':_("please enter a username"), 'min_length':_("username must be at least 5 characters"), 'max_length':_("username must be at less than 30 characters")})
  23. password = forms.CharField(min_length=6, error_messages={'required':_("please enter a password"), 'min_length':_("password must be at least 6 characters")})
  24.  
  25. def clean(self):
  26. username = self.cleaned_data.get('username')
  27. password = self.cleaned_data.get('password')
  28.  
  29. if username and password:
  30. self.user_cache = authenticate(username=username, password=password)
  31. if self.user_cache is None:
  32. raise forms.ValidationError(_("you have entered an incorrect username and/or password"))
  33. elif not self.user_cache.is_active:
  34. raise forms.ValidationError(_("This account is inactive."))
  35. self.check_for_test_cookie()
  36. return self.cleaned_data
  37.  
  38. from django.contrib.auth.forms imoirt AuthenticationForm
  39. from django.contrib.auth import login as auth_login
  40.  
  41. # in the view
  42. if request.method == "POST":
  43. form = AuthenticationForm(data=request.POST)
  44. if form.is_valid():
  45. # if the form is valid, the user has provided a valid
  46. # username and password. We can get the user with the
  47. # form.get_user method and log them in
  48. auth_login(request, form.get_user())
  49. # return suitable ajax responses
Add Comment
Please, Sign In to add comment