My project has a Post model. My home page has list of all post and post_create form. I create post using ajax view. Intention was to create a new post and update the home page without page refresh. Here is the code, views.py,
def post_create_ajax(request):
if request.is_ajax():
if request.method == 'POST':
title = request.POST.get('the_post')
author = request.user
post = Post(title=title, author=author)
print(title)
post.save()
return JsonResponse({'title': title})
The script,
$('#postform').submit(function(event){
event.preventDefault();
console.log('Working');
create_post();
});
function create_post(){
console.log('Create Post is working');
var posttitle = $('#id_title').val();
$.ajax({
url: '/ajaxcreate/',
type: "POST",
data: {
the_post: posttitle,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
dataType: 'json',
success: function(data){
$('#id_title').val('');
console.log(data.title);
$('#post_title_content').html(data.title);
},
error:function(){
console.log('Error Occoured');
alert('Error');
},
})
}
This part works fine. The page new post is getting added without refresh.
Here is a problem. After I submit a post, the new title that getting added are not safe.
e.g. if I add <b> This is a title </b>
, The new div is added with This is a title and only returns to plain text <b> This is a title </b>
after I refresh the page.
So my question is how to change my script so that it will update div as plain text?
Images:
New post is added, but not in plain text,
After I refresh it shows as plain text,