【发布时间】:2021-12-14 02:04:11
【问题描述】:
我想在 jquery click 上显示错误的登录错误。我的代码工作正常,jquery event(click) 按钮显示响应也正确但 django 视图没有正确呈现响应。在检查元素中的响应中,它们显示错误为我发送上下文,但更改未显示在屏幕上。
登录视图
def logn(req):
if req.user.is_authenticated:
return redirect('home')
if req.method == 'POST':
usrname = req.POST['lusername']
psswd = req.POST['lpass']
if len(psswd) == 0:
print('error')
context={
'error_msg':'password?'
}
return render(req,'base.html',context)
usr = authenticate(req,username=usrname,password=psswd)
if usr is not None:
login(req,usr)
redirect('home')
jQuery
$('#lbtn').click(function(){
let lusername = $('input[name=lusername]').val();
let lpass = $('input[name=lpassword]').val();
$.ajax({
type: 'POST',
url: '/login/',
headers :{
'X-CSRFToken': getcsrfToken(),
},
data: {
lusername : lusername,
lpass : lpass,
},
success: (data) => {
if(data){
$('input[name=lusername]').val('');
$('input[name=lpassword]').val('');
}
},
})
})
HTML
<div class='bg'>
<span><i class='material-icons tiny left cross'>clear</i></span>
<i class='material-icons tiny right spin'>cached</i>
{% if error_msg %}<p class='red-text'>{{error_msg}}</p>{% endif %}
</div>
<div class='white-text log_title'>
LOGIN
</div>
<div class='white-text log_title1'>
Please enter your username and password
</div>
{% if error_msg %} <p class='red-text'>{{ error_msg }}</p>{% endif %}
{% csrf_token%}
<div class="row">
<div class="input-field col s9">
<p for="lusername" class='white-text log_user'>Username</p>
<input name='lusername' type="text" class="validate white-text" id='in1'>
</div>
</div>
<div class="row">
<div class="input-field col s9">
<p for="lpassword" class='white-text log_user'>Password</p>
<input name='lpassword' type="text" class="validate white-text" id='in1'>
</div>
</div>
<div class='center'>
<button class="btn waves-effect waves-light blue black-text" type="submit" name="action" id='lbtn'>
Login
</button>
</div>
<div class='topper'>
<a href='/'>
Forgot Password ?
</a>
</div>
</div>
登录模式位于“base.html”中。因此,我必须在具有不同上下文的不同视图中呈现“base.html”。
【问题讨论】: