== Adding an ajax login form to your project == Assuming you have a project running and using the normal authentification scheme providen by django, it would be nice not to reload the page to show errors about login and password when the login is wrong. We need to add a specific method to your application's view.py for this example we will call the method '''loginajax'''. We simply do a copy / past from '''/django/contrib/auth/view.py''' method login. we will modify the return values. {{{ #!python def loginajax(request): manipulator = AuthenticationForm(request) redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '') if request.POST: errors = manipulator.get_validation_errors(request.POST) if not errors: if not redirect_to or '://' in redirect_to or ' ' in redirect_to: redirect_to = '/accounts/profile/' request.session[SESSION_KEY] = manipulator.get_user_id() request.session.delete_test_cookie() return HttpResponse(redirect_to) else: return HttpResponse("false") }}} Now let change our '''url.py''' You should still keep the normal {{{r'^login/$'}}} entry and add the new one. {{{ #!python [..] (r'^login/$', 'django.contrib.auth.views.login'), (r'^login/ajax/$', 'cefinban.views.loginajax'), [...] }}} We then need to add the dojo magic to our login page. id = loginForm refer to our
If you are confused see [wiki:AjaxDojoFormSub], similar code is more detailed there. {{{ var sendLoginButton; function sendLogin(){ dojo.io.bind({ url: '/login/ajax/', handler:sendLoginCallback, formNode: dojo.byId('loginform'), method: 'POST' }); // let hide the form dojo.byId("loginform").style.display = "none"; dojo.byId("messagestatus").innerHTML = "

Loading ...

"; } function sendLoginCallback(type, data, evt) { if (type == 'error') alert('Error when retrieving data from the server!'); else if (data === "false") { dojo.byId("loginform").style.display = ""; dojo.byId("messagestatus").innerHTML = " Your password or username is invalid"; dojo.event.disconnect(sendLoginButton, 'onclick', 'sendLogin'); var anim = dojo.lfx.html.highlight("messagestatus", [255, 0, 0], 200).play(100); dojo.event.connect(anim, "onEnd", function() { dojo.event.connect(sendLoginButton, 'onclick', 'sendLogin'); }); } else { window.location=data; } } function init(){ sendLoginButton = dojo.byId('loginButton'); // disable form posting when js used var loginForm = dojo.byId('loginform'); loginForm.onsubmit = function() { return false; } dojo.event.connect(sendLoginButton, 'onclick', 'sendLogin'); } dojo.addOnLoad(init); }}} Note you can go further by not redirecting to a login_ok page but updating the appropriate field, like the header part of your page telling you if you are a registred user or not (if you have such a thing). Demo : [http://www.cefinban.net/login]