我想知道如果你們能與我分享你在Django中顯示警報和確認消息的策略。我真的不確定什麼是實現這一目標的最佳方式。你是否將一個單獨的.py文件與消息和一個包裝函數保存在一起,或者你只是沿代碼硬編碼一切?你認爲這應該是在視圖或模板中的優先事項?實現確認和提醒消息的最佳方式
無論如何,謝謝。
我想知道如果你們能與我分享你在Django中顯示警報和確認消息的策略。我真的不確定什麼是實現這一目標的最佳方式。你是否將一個單獨的.py文件與消息和一個包裝函數保存在一起,或者你只是沿代碼硬編碼一切?你認爲這應該是在視圖或模板中的優先事項?實現確認和提醒消息的最佳方式
無論如何,謝謝。
我使用了重新使用視圖顯示確認
重新使用視圖
def bootstrap_confirm(
request,
heading,
message,
yes_color='success',
yes_text='Yes',
cancel_color='danger',
cancel_text='No',
cancel_url='',
box_color='info',
base_name='base.html'):
if request.method == 'POST':
confirm = request.session['confirm_value']
assert request.POST.get('confirm') == confirm, "Error"
return request.POST.get('submit_button') == yes_text
else:
confirm = get_random_string(16)
request.session['confirm_value'] = confirm
return render_to_response('django-helpers/twitter-bootstrap/confirm.html', request, {
'confirm_value': confirm,
'confirm_heading': heading,
'message': message,
'base_name': base_name,
'box_color': box_color,
'yes_color': yes_color,
'yes_text': yes_text,
'cancel_color': cancel_color,
'cancel_text': cancel_text,
'cancel_url': cancel_url,
})
重新使用的模板
{% extends base_name %}
{% block main-contents %}
<h2>{{ confirm_heading }}</h2>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="confirm" value="{{ confirm_value }}">
<div class="alert alert-{{ box_color|default:"info" }}">
<div>{{ message }}</div>
<br>
<div>
<input type="submit" class="btn btn-{{ yes_color|default:"success" }}" name="submit_button" type="submit" value="{{ yes_text|default:"Yes" }}">
{% if cancel_url %}
<a href="{{ cancel_url }}" class="btn btn-{{ cancel_color|default:"danger" }}">{{ cancel_text|default:"No" }}</a>
{% endif %}
</div>
</div>
</form>
{% endblock %}
查看
def confirm(request):
msg = '...'
heading = '...'
op = bootstrap_confirm(request, heading, msg)
if isinstance(op, HttpResponse):
return op
if op == True:
# Implement custom logic
elif op == False:
# Implement custom logic
您也可以使用類似的可重用視圖來顯示消息。此代碼來自我的圖書館django-helpers。我也有興趣瞭解更多的策略。糾正我,如果我錯了?
Django帶有一個messages
應用程序,可以幫助解決這個問題。
在你看來,你想補充一點,你需要顯示的消息:
from django.contrib import messages
from django.shortcuts import render
def someview(request):
# your normal code
messages.add_message(request, messages.INFO, 'Yeehaw!')
return render(request, 'sometemplate.html')
注意我沒有在我看來返回的消息,這是因爲messages middleware需要照顧這對我來說。我只需要返回RequestContext
,即render
shortcut。
在模板:
{% if messages %}
{% for message in messages %}
<div{% if message.tags %} class="alert alert-{{ message.tags }}"{% endif %}>
<a class="close" data-dismiss="alert" href="#">×</a>
{{ message }}
</div>
{% endfor %}
{% endif %}
通常你把上面的代碼中的每一個模板,從繼承您的基本模板之一;就是這樣。
並且爲了顯示帶引導程序樣式的錯誤消息,您應該將此行添加到settings.py中:'MESSAGE_TAGS = {message.ERROR:'danger' }'MESSAGE_TAGS = {} – 2017-03-30 09:14:47