Django: How to insert data or get/post request without reloading or refreshing page.
Creating GET/POST request with jQuery to prevent page reload.
I made a blog and also a comment system but, there was a problem. Whenever I filled the form and click submit button browser was reloading the page. So I decided to fill the form in an another way and show a snackbar alert telling the response of my server after I’ve clicked on the button.
Here is how we do it.
Define a new function to handle specific forms/requests
#Add this in views.py
#.......
#....... Your views
#jQuery post request handling.def new_comment(request):
if request.method == 'POST':
create_comment = Comment()
create_comment.post_id = get_object_or_404(Post, slug=request.POST['post_slug'])
create_comment.user = request.POST['user_name']
create_comment.email = request.POST['email']
create_comment.comment = request.POST['comment_body']
try:
if request.POST['reply'] == 'true':
create_comment.reply = True
create_comment.main = request.POST['reply_to']
elif request.POST['reply'] =='false':
print('new comment')
except:
retun HttpResponse('Can\'t process your request. Try again')
if len(Comment.objects.filter(email=request.POST['email'])) != 0:
create_comment.valid = True
else:
create_comment.save()
return HttpResponse('Comment is being reviewd')
create_comment.save()
return HttpResponse('Commented Successfully')
Add a new url in your website.
In urls.py add a line like this
#imports...urlpatterns = [
path('', views.index),
path('post/<str:slug>', views.post),
#other paths...
path('post_comment/', views.new_comment), #new
]
Create a form in html.
There are many ways to send POST/GET requests and it is not mandatory to create fields in <form> tag you can also use <div> tag containing all the form fields as we are not posting the content with traditional way.
Download or Embed jQuery in you html
You can either download or use CDN for jQuery.min.js. Using google’s CDN will be a good Idea. You can include jquery by adding this text in <head> section of your website:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Get data from form fields and post to server.
Adding jQuery will make it a lot easier to get data from form fields and post them on the server. We use ‘$’sign to show jQuery.
We know that Django have great security so it become complicated to POST the data. Use {% csrf_token %} in template html file where the form exists. Now with jQuery we will get all the data from form fields when Submit button is clicked add attribute onclick=“post_comment()”.
function post_comment() {
$.post(
'/post_comment/',{
reply: false,
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val(),
user_name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
comment_body: $('textarea[name="body"]').val(),
post_slug: $('input[name="slug"]').val()
},
function (data) {
alert(data);
}
);
}
Hope you’ll like the post.
Thanks for reading