I am using AjaxForm plugin to submit my form without refresh. like:
$('#my_form_id').ajaxForm(function(){
//something on success or fail
});
this works correctly. when i click submit button it saves form datas without refresh. But before this ; i had django messages on my template file like:
{% for message in messages %}
<div id="notice" align="center">
{{ message }}
</div>
{% endfor %}
what this code does is displaying notifications if post saved correctly or something failed.
now; i can’t do that. i dont understand how i can use these messages tags with ajax functions.
it just saves the post. no notifications.
thank you.
edit :
add_post url : url(r'^admin/post/add/$', view='add_post',name='add_post'),
related view :
@login_required(login_url='/login/')
def add_post(request):
template_name = 'add.html'
owner = request.user
if request.method == "POST":
form = addForm(request.POST)
if form.is_valid():
titleform = form.cleaned_data['title']
bodyform = form.cleaned_data['body']
checkform = form.cleaned_data['isdraft']
n = Post(title=titleform, body=bodyform, isdraft=checkform, owner=owner)
n.save()
messages.add_message(request, messages.SUCCESS,
'New post created successfully!')
else:
messages.add_message(request, messages.WARNING,
'Please fill in all fields!')
else:
form = addForm()
return render_to_response(template_name, {'form': form, 'owner': owner,},
context_instance=RequestContext(request))
These are the tools/methods that helped me to solve the problem. First, I have a helper utility method called
render_to_json:I have a
messages.htmltemplate to render the necessary html for the popup message(s):When create a message in response to an AJAX request, I use Django’s
render_to_stringto package the message(s) into a string that gets stored in adatadictionary, which then uses myrender_to_jsonto return an appropriate response:Then, in my jQuery
$.post(...)callback function, I check to see if theresponseobject has amsgattribute, and then insert the contents ofresponse.msginto the DOM where I want it needs to be, with jQuery transitions if desired. Mybase.htmltemplate contains the<ul>container for the messages:Note that the above includes the
messages.htmlfor 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: