Tôi thích ý tưởng sử dụng khung thư nhưng ví dụ trong tài liệu django không hoạt động đối với tôi trong ngữ cảnh của câu hỏi ở trên.
Điều gì thực sự làm phiền tôi, là dòng trong tài liệu django:
If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
đó là không thể hiểu được để một newbie (như tôi) và cần phải mở rộng khi, tốt hơn với những gì những 2 lựa chọn như thế nào .
Tôi chỉ có thể tìm thấy các giải pháp yêu cầu hiển thị với RequestContext ... không trả lời câu hỏi ở trên.
Tôi tin rằng tôi đã tạo giải pháp cho tùy chọn thứ 2 bên dưới:
Hy vọng điều này sẽ giúp người khác.
== urls.py ==
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
(r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
(r'^test/$', test),
== viewtest.py ==
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def test(request):
messages.success(request, 'Test successful')
return HttpResponseRedirect(reverse('main_page'))
== viewmain.py ==
from django.contrib.messages import get_messages
from django.shortcuts import render_to_response
def main_page(request, template_name):
# create dictionary of items to be passed to the template
c = { messages': get_messages(request) }
# render page
return render_to_response(template_name, c,)
main_page.html == ==
{% block content %}
{% if messages %}
<div>
{% for message in messages %}
<h2 class="{{message.tag}}">{{ message.message }}</h2>
{% endfor %}
</div>
{% endif %}
{% endblock %}
Tôi nghĩ vấn đề này khá phổ biến trong mọi khung công tác và không giới hạn ở django/python. – Jiri
@Jiri, vâng, nhưng một số khung công tác cung cấp hỗ trợ cho nó. –
mã hóa thư trong chuỗi truy vấn của url bạn đang chuyển hướng đến. nên làm việc trong bất kỳ khung công tác nào. –