[英]Send only specific value to server in Django
I have a html code like this: 我有这样的html代码:
{% 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: 如果我按下user3的跟随按钮,我只想发送user3的ID,这样我就可以像这样在服务器中访问它:
followed_user = request.POST['follow_id']
# Process
But, no matter which follow_button I press, I get the user id of only user1. 但是,无论我按哪个跟随按钮,我都只能获得user1的用户ID。 How to fix this?
如何解决这个问题?
This is not a Django issue, but a HTML issue. 这不是Django问题,而是HTML问题。 Here is the work around: 1 form for each user:
解决方法:每个用户1个表单:
{% 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 ! 请注意,所有表单都提交到相同的URL ,因此具有相同的视图功能 !
Just my 2 cents, I would use some jQuery for this job. 仅花2美分,我会为此工作使用一些jQuery。
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: 然后使用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?
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.