简体   繁体   中英

Send only specific value to server in Django

I have a html code like this:

{% for i, j, k in full_name %}
    {{ i }} {{ j }} 
    <input type="text" name="follow_id" value="{{ k }}" />
    <input type="submit" value="Follow"><br /> <br />   

{% endfor %}

The output looks like this:

user1 user_id_of_user1 follow_button

user2 user_id_of_user2 follow_button

user3 user_id_of_user3 follow_button

If I press the follow button of user3 I want to send the id of user3 only so that I can access it in server like this:

followed_user = request.POST['follow_id'] 
# Process

But, no matter which follow_button I press, I get the user id of only user1. How to fix this?

This is not a Django issue, but a HTML issue. Here is the work around: 1 form for each user:

{% for i, j, k in full_name %}
    <form action="mydomain.com/mysubmiturl/" method="POST"><!-- Leave action empty to submit to this very same html -->
        {% csrf_token %} <!-- Django server only accept POST requests with a CSRF token -->
        {{ i }} {{ j }} 
        <input type="text" name="follow_id" value="{{ k }}" />
        <input type="submit" value="Follow"><br /> <br />
    </form>
{% endfor %}

Note that all the forms submit to the same URL , and thus the same view function !

Just my 2 cents, I would use some jQuery for this job.

In your template:

{% for i, j, k in full_name %}
    {{ i }} {{ j }} 
    <a href="#" id="js-follow-{{ k }}" class="follow-button">Follow</a>
{% endfor %}

Then submit the data using AJAX:

$('.follow-button').click(function (e) {
    e.preventDefault();
    var this_id = $(this).attr('id').replace('js-follow-', '');    

    $.ajax({
        type: 'POST',
        url: 'path/to/view',
        data: {'follow_id': this_id},
        success: function (resp) {
            // do something with response here?    
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM