![](/img/trans.png)
[英]Django celery redis, recieved task, but not success not fail message, how to fix?
[英]How to use toastr in Django for success or fail message
我一直在使用Django消息框架在我的應用程序中顯示成功或失敗消息。 但是我希望UI很好,所以我發現toastr是向用戶顯示消息的好方法。 但是我不確定如何使用它。 請指導我。
下面的函數將用戶保存到數據庫,並在保存用戶信息時顯示一條消息:
def addSubscriber(request):
template = 'addSubscriber.html'
if request.method == 'POST':
form = addSubsForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.save()
messages.success(request, "The Subscriber has been successfully added")
return redirect('report')
else:
messages.error(request, "Sorry the data has not been entered to the database")
else:
form = addSubsForm()
return render(request, template, {'form': form})
以下模板顯示了消息的顯示:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
在HTML代碼中添加Toastr js和CSS,然后在下面的代碼中顯示toastr消息
{% for message in messages %}
toastr.{{ message.tags }}({{ message }});
{% endfor %}
感謝這個問題,我能夠用python實現toastr
,這是Neeraj Kumar提供的更完整的答案。
就我而言,這比實現要好得多,因為該CSS套件會破壞我自己的CSS代碼,並且我沒有時間進行CSS調試。
首先 ,您必須在模板中設置JS文件 ,例如:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'css/toastr.css' %}" media="all">
<script type="text/javascript" src="{% static 'js/toastr.min.js' %}"></script>
接下來, 您可以在主體內部放置Toast消息的選項(可以在Toastr演示頁面中輕松創建這些選項。
最后,如果您使用的是來自django的消息框架的標准標簽,請插入以下代碼塊 :
{% if messages %}
{% for message in messages %}
{% if message.tags == 'success'%}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'info' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'warning' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% elif message.tags == 'error' %}
<script type=text/javascript>toastr.{{ message.tags }}('{{ message }}')</script>
{% endif %}
{% endfor %}
{% endif %}
我希望這對其他人有幫助並節省時間。
不錯的方法,只是忘了在消息中包含引號“”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.