我已经花了几天无济于事,想知道是否有人可以帮助我?我试图将 Django 用作后端,最终目标是移植到移动应用程序。我在前端有一个表单和 ajax 调用到 Django 中的 url/view(REST API 以及如果相关),但由于某种原因,我不明白该调用不会让我登录.
相关应用:
- Django-Userena
- 好吃的
谁能建议我正确的方向?下面是代码,谢谢!
索引.html
<script>
$(document).ready(function(){
`//login test`
`$('#login').submit(function(){`
$.ajax({
url: 'http://127.0.0.1:8000/accounts/signin/',
type: 'POST',
//data: loginString,
data: $('#login').serialize(),
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});
});
});
</script>
</head>
<body>
<div id="datadisplay"></div>
<input type="submit" id="getdata" value="Submit">
<div id="loginform">
<form name="login" id="login" action="">
<fieldset>
<label for="id_identification">Username</label>
<input type="text" name="identification" id="id_identification" size="30" value="" />
<br/>
<label for="id_password">Password</label>
<input type="password" name="password" id="id_password" size="30" value="" />
<br/>
<input type="submit" name="submit" class="loginbutton" value="Login" />
</fieldset>
</form>
</div>
api.py
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
include_resource_uri = False
allowed_methods = ['get', 'post']
def override_urls(self):
return [url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )