Django 消息仅显示在管理员中
Django Messages show up only in admin
我已经设置了一条 django 消息,当用户登录时会显示该消息,但消息仅在管理员中显示。
accounts/views.py
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form':form
}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username,password=password)
if user is not None:
login(request, user)
try:
del request.session['guest_email_id']
except:
pass
if is_safe_url(redirect_path,request.get_host()):
return redirect(redirect_path)
else:
messages.info(request,"You are now logged in")
return redirect("/")
else:
messages.error(request,"Something went wrong")
print("Error")
return render(request,"accounts/login.html", context)
settings.py
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
'OPTIONS': {
'context_processors': [
...
'django.contrib.messages.context_processors.messages',
base.html
{% if message is not None %} {% for message in messages %}{{ message }}{% endfor %}{% else %}{% endif %}
您应该删除 {% if message is not None %}
条件。特别是因为在 that 点,消息还没有定义。您可以检查消息<b>s</b>
。但是你不应该检查 None
,而只是检查真实性,比如:
{% if <b>messages</b> %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
如果您不想在这些消息周围呈现某些内容(例如 <ul> … </ul>
),您可以简单地省略 {% if %} … {% endif %}
)。
有关详细信息,请参阅 documentation on displaying messages。
我已经设置了一条 django 消息,当用户登录时会显示该消息,但消息仅在管理员中显示。
accounts/views.py
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form':form
}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username,password=password)
if user is not None:
login(request, user)
try:
del request.session['guest_email_id']
except:
pass
if is_safe_url(redirect_path,request.get_host()):
return redirect(redirect_path)
else:
messages.info(request,"You are now logged in")
return redirect("/")
else:
messages.error(request,"Something went wrong")
print("Error")
return render(request,"accounts/login.html", context)
settings.py
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
'OPTIONS': {
'context_processors': [
...
'django.contrib.messages.context_processors.messages',
base.html
{% if message is not None %} {% for message in messages %}{{ message }}{% endfor %}{% else %}{% endif %}
您应该删除 {% if message is not None %}
条件。特别是因为在 that 点,消息还没有定义。您可以检查消息<b>s</b>
。但是你不应该检查 None
,而只是检查真实性,比如:
{% if <b>messages</b> %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
如果您不想在这些消息周围呈现某些内容(例如 <ul> … </ul>
),您可以简单地省略 {% if %} … {% endif %}
)。
有关详细信息,请参阅 documentation on displaying messages。