I am learning Django2,and try to make a login page with csrf_token and ajax.
I hope that if user hasn't lgoin,that will turn to the login page and send a variable next
as a tag of the page before login.If user login successfully that I can turn to the homepage or page marked by next
.
I read the docs of Django2, and try to code like below,however,when I click "LOGIN" button,it just refresh the login page and get no error
I am confused and have no idea already.Please help.
login views:
def login(request):
if request.is_ajax():
uf = UserForm(request.POST)
if uf.is_valid():
# get info from form
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
user = auth.authenticate(request, username=username, password=password)
if user is not None: # user match
auth.login(request, user)
if request.GET.get('next'):
next_url = request.GET.get('next')
return JsonResponse({'redirect_url': next_url})
# return redirect(request.GET.get('next'))
else:
return JsonResponse({'redirect_url': 'home'})
else: # user not match
error_msg = ["username or pwd mistake"]
return JsonResponse({'error_msg': error_msg})
else:
uf = UserForm()
return render(request, 'login.html', {'uf': uf})
html :
<form>
{% csrf_token %}
{{ uf.username }}
{{ uf.password }}
<div id="errorMsg"></div>
<button type="submit" class="btn btn-default" id="loginButton">login</button>
<input type="hidden" name="next" id="redirect-next" value="{{ next|escape }}"/>
</form>
JQuery:
$("#loginButton").click(function () {
$.ajax({
url: "",
type: 'POST',
dataType: "json",
data: {username: $("#inputEmail3").val(), password: $("#inputPassword3").val()},
beforeSend: function (xhr, settings) {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (result) {
if (result.error_msg) {
$('#errorMsg').show().text('user info error') //print an alert on the page
}
else {
location.href = result.redirect_url //turn to homepage or page before login
}
}
})
});