Django Login with Ajax?

I am working on a jquery function to submit a login form using ajax. The success of ajax: I want to handle the response in different ways if it is a successful login or not.

So, in Django, I am wondering if I can build an existing input view to add some success / error variable, to send back the jquery functions along with the returned page. I mean to keep the view as it works by default, but also add an additional status variable.

A small example of this will be great!

+6
source share
2 answers

You need to set up a jquery Ajax call to publish in your Login view in django.

In the view, you need to do something like this ...

import json from django.http import HttpResponse def login(request): if request.method == 'POST': login_form = AuthenticationForm(request, request.POST) response_data = {} if login_form.is_valid(): response_data['result'] = 'Success!' response_data['message'] = 'You"re logged in' else: response_data['result'] = 'failed' response_data['message'] = 'You messed up' return HttpResponse(json.dumps(response_data), content_type="application/json") 

I have not tested this, but you ajax call should look something like this.

 <script> $.ajax({ type:"POST", url: 'http://www.yousite.com/yourview/login/', data: $('#login_form').serialize(), success: function(response){ // do something with response response['result']; // equals 'Success or failed'; response['message'] // equals 'you"re logged in or You messed up'; } }); </script> 
+3
source

your view.py

 def logmein(request): username= request.GET.get('username') password = request.GET.get('pwd') stayloggedin = request.GET.get('stayloggedin') if stayloggedin == "true": pass else: request.session.set_expiry(0) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse('fine') else: return HttpResponse('inactive') else: return HttpResponse('bad') 

your ajax

 function logmein() { var username = $.trim($('#username').val()); var pwd = $.trim($('#pwdlogin').val()); var stayloggedin = document.getElementById('stayloggedin').checked; $.ajax({ url : "/logmein/", type : "get", data : { username: username, pwd : pwd, stayloggedin : stayloggedin, next : next } }).done(function(data) { if (data == "fine") { window.location = window.location; } }); } 
+1
source

Source: https://habr.com/ru/post/978189/


All Articles