These are the tools/methods that helped me to solve the problem. First, I have a helper utility method called render_to_json
:
# `data` is a python dictionary
def render_to_json(request, data):
return HttpResponse(
json.dumps(data, ensure_ascii=False),
mimetype=request.is_ajax() and "application/json" or "text/html"
)
I have a messages.html
template to render the necessary html for the popup message(s):
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
When create a message in response to an AJAX request, I use Django's render_to_string
to package the message(s) into a string that gets stored in a data
dictionary, which then uses my render_to_json
to return an appropriate response:
def my_custom_view(request)
# ... your view code
data = {
'msg': render_to_string('messages.html', {}, RequestContext(request)),
}
return render_to_json(request, data)
Then, in my jQuery $.post(...)
callback function, I check to see if the response
object has a msg
attribute, and then insert the contents of response.msg
into the DOM where I want it needs to be, with jQuery transitions if desired. My base.html
template contains the <ul>
container for the messages:
<ul id="popup-messages-content">
{% include 'messages.html' %}
</ul>
Note that the above includes the messages.html
for the case when you want to display messages on an actual page load (non-AJAX request) - it is blank if there are no messages, but the <ul>
is still available to push AJAX-received messages into.
The last piece is the Javascript function (requires jQuery) I use in any $.post(...)
callbacks to show the messages:
function showPopupMessage(content) {
var elMessages = $('#popup-messages-content');
if (elMessages.length && content) {
elMessages.html(content);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…