SJ1*_*J19 3 html python django login http
我正在尝试登录我的Django(2.0)网站,到目前为止我已经登录了现有帐户.我正在使用内置登录功能.
现在,我想在您输入无效帐户时显示错误消息,例如"无效的用户名或密码!".但我不知道该如何解决这个问题.
现在它只是在您输入无效帐户时刷新登录页面.任何帮助表示赞赏!
的login.html
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
登录视图
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')
else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)
在您的模板中
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
鉴于
from django.contrib import messages
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')
else:
messages.error(request,'username or password not correct')
return redirect('login')
else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)
您应该只在模板中添加:
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
{% if form.errors %}
<p>username or password not correct</p>
{% endif %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11698 次 |
| 最近记录: |