Simeon Kostadinov Simeon Kostadinov - 1 year ago 137
Ajax Question

Django: make a POST request on form submit without reloading the page or rendering to another?

I have been struggling with this problem for more than two days, I have looked at similar questions here and to many documentations but nothing helped me. Basically, I am building a Django web application (where people can add themselves as friends) I am using Django package django-friendship, but I want the following to happen: when a user is in someone else profile, the first can click an 'Add friend' button and a friend request must be sent. But I want to achieve this without reloading the page or rendering to another one. The method that has to be triggered in order to send the request is in Probably I need to use ajax but in what way? My final goal is the button to perform as an 'Add friend' button in facebook, for example (without reloading).


<form action="{% url 'users:fr_request' %}" method="POST">
{% csrf_token %}
<input type="submit" value="Add friend"/>

def friendship_add(request, pk):
if request.method == 'POST':
to_user = User.objects.get(pk=pk)
from_user = request.user
Friend.objects.add_friend(from_user, to_user)
except AlreadyExistsError as e:
print('Exception when adding a friend ' + e)
return HttpResponse('You added a friend')

return render(request, 'users/friend_profile.html')

urlpatterns = [
url(r'users/(?P<pk>\d+)/send/$', views.friendship_add, name='fr_request'),


At the moment when submitting the form, I render the page to users/(?P\d+)/send/ which calls the view method and executes Friend.objects.add_friend, but I want this to happen without going to /send/ page or reloading the current?

Answer Source

This can be easily achieved using jQuery. You may want to assign an id to your form in case there are multiple forms in your page:

<form action="{% url 'users:fr_request' %}" method="POST" id="friend_form">
    {% csrf_token %}
<input type="submit" value="Add friend"/>

The script could then look like that:

$(function() {
    $("#friend_form").submit(function(event) {
        // Stop form from submitting normally
        var friendForm = $(this);
        // Send the data using post
        var posting = $.post( friendForm.attr('action'), friendForm.serialize() );
        // if success:
        posting.done(function(data) {
            // success actions, maybe change submit button to 'friend added' or whatever
        // if failure: {
            // 4xx or 5xx response, alert user about failure

For more information and examples refer to the documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download