主要用在view.login函数,不管登录是否成功,都会设置message变量,然后在login.html显示
from django.contrib import messages#需要导的包
提供两个函数
messages.add_message(request,messages.INFO,'要显示的字符串')
messages.get_messages(request)
默认类型有:(message.INFO)
- DEBUG
- INFO
- SUCCESS
- WARNING
- ERROR
也可以在setting.py中自定义自己的等级标签
附上我的代码
def login_2(request):
if request.method == 'POST':
login_form = LoginForm(request.POST)
if login_form.is_valid():
login_name=request.POST['username'].strip()
login_password = request.POST['password']
user = authenticate(username=login_name,password=login_password)
if user is not None:
if user.is_active:
auth.login(request,user)#把此用户的数据存入session中
print "success"
messages.add_message(request,messages.SUCCESS,'成功登陆了')#使用了django的信息显示框架 message framework
return HttpResponseRedirect('/userinfo/')
else:
messages.add_message(request,messages.WARNING,"账号尚未启动")
else:
messages.add_message(request,messages.WARNING,"登陆失败")
else:
messages.add_message(request,messages.INFO,"请检查输入的字段内容")
else:
login_form = LoginForm()
template = get_template('one/agriculture/login.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for message in messages %}
<div class='alert alert-{{message.tags}}'>{{ message }}</div>
{% endfor %}
<!--主要是结合message framework 用-->
<p>登陆我的农商</p>
<form action="/login_2/" method="post">
{% csrf_token %}
<table>
{{ login_form.as_table }}
</table>
<input type="submit" value="登陆" />
</form>
</body>
</html>
- 截图