最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 views.py. 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).

friend_profile.html

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

views.py

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

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

urls.py

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?

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 views.py. 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).

friend_profile.html

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

views.py

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

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

urls.py

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?

Share asked Jul 22, 2016 at 12:34 Simeon KostadinovSimeon Kostadinov 331 silver badge5 bronze badges 4
  • Well, your tags include "ajax", and that is indeed what you will need to use. What have you tried? – Daniel Roseman Commented Jul 22, 2016 at 12:40
  • I have tried proceeding the form with ajax and the data needed but it requires 'url' which I want to avoid because it will call the url (then the view and so on) and the new page will still render - which I don't want? How do you think can be done? – Simeon Kostadinov Commented Jul 22, 2016 at 13:10
  • I don't understand what you're saying. Your Ajax script should post to a view which returns the data needed by the JS to update the page without reloading. – Daniel Roseman Commented Jul 22, 2016 at 13:14
  • Sorry for the ambiguity, perhaps I have misunderstood something, now it works when I tried @rafalmp code! – Simeon Kostadinov Commented Jul 22, 2016 at 13:50
Add a ment  | 

1 Answer 1

Reset to default 9

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' pk=friend.id %}" 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
        event.preventDefault();
        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:
        posting.fail(function(data) {
            // 4xx or 5xx response, alert user about failure
        });
    });
});

For more information and examples refer to the jQuery.post() documentation.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论