我试图在我的主页上显示警报,当有人成功登录或注销,并显示一个错误警报,如果有什么问题登录。除了登录和注销视图外,我的所有消息警报都与我的所有视图一起工作,我不知道为什么。
视图:
def用户_(请求):
data = cartData(request)
cartItems = data['cartItems']
context = {
'cartItems': cartItems,
}
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request,"You were successfully logged in...")
return redirect('home')
else:
messages.success(request, ("There was an error logging in, please try again..."))
return redirect('login')
return render(request, 'registration/login.html', {'context': context})
def user_logout(请求):
logout(request)
messages.info(request, ("You were successfully logged out..."))
return redirect('home')
HTML:
{% if messages %}
<div class="alert alert-success" id="msg" role="alert">
<h4 class="alert-heading">Success</h4>
{% for message in messages %}
<p>{{message}}</p>
{% endfor %}
</div>
{% endif %}
编辑:添加了正常工作的视图
def UserRegister(请求):
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, ("Registration successful, you are now logged in..."))
return redirect('home')
else:
form = UserRegisterForm()
return render(request, 'authenticate/register.html', {'form': form})
您需要像这样实现html代码来显示消息:
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
我很确定它会起作用。您可以先这样测试,然后根据您的前端需求相应地实现它。