通过Django All-auth上的AJAX发布请求登录 [英] Signing in through AJAX post request on Django All-auth
问题描述
根据django all-auth的文档,它支持通过AJAX请求登录.当我向"accounts/login/"发出普通的发布请求时,响应头的内容类型为"text/html".但是当我进行ajax调用时,它是"application/json".我无法弄清楚自己在做什么错,我曾尝试在ajax调用中更改contentType和dataType,但它给出了400错误的请求错误.
According to the documentation of django all-auth , it supports logging in through AJAX requests.When I make a normal post request to "accounts/login/" ,content type of the response header is "text/html". But when I make a ajax call it is "application/json". I am unable to figure what I am doing wrong, I have tried changing the contentType and dataType in ajax call but it gives a 400 Bad request error.
我还没有修改默认Django all-auth应用程序的任何URL或视图.
I have not modified any URL or view of the default Django all-auth app.
我在此处包含JavaScript代码-
I am including the JavaScript code here -
<script type="text/javascript">
var $button = $('#login_button');
$button.on('click',function(){
var data = {"csrfmiddlewaretoken" : document.getElementsByName('csrfmiddlewaretoken')[0].value,
"login": $('#id_login').val(),
"password": $('#id_password').val(),
"remember": $('#id_remember').val() };
var temp = {'X-CSRFToken': document.getElementsByName('csrfmiddlewaretoken'[0].value };
$.post({
url : "{% url 'account_login' %}",
headers: temp,
type: "POST",
data : data,
contentType: "application/x-www-form-urlencoded",
dataType: "text",
success : function(data) {
// console.log(data);
},
});
});
</script>
推荐答案
我遇到了类似的问题,对我来说,这个解决方案(不是一种很好的方法,但是很有效):-在adapter.py中,您可以查看表单是否无效,状态为400,并且我也更改了数据
I had similar issue and for me worked this solution (not a nice way but worked): - in adapter.py you can see if form is not valid, status 400 and i have also changed the data
def ajax_response(self, request, response, redirect_to=None, form=None):
data = {}
status = response.status_code
if redirect_to:
status = 200
data['location'] = redirect_to
if form:
if form.is_valid():
status = 200
else:
status = 200
data['form_errors'] = form._errors
if hasattr(response, 'render'):
response.render()
data = response.content
return HttpResponse(json.dumps(data),
status=status,
content_type='application/json')
这篇关于通过Django All-auth上的AJAX发布请求登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!