【问题标题】:How to get specific id from for loop in django template?如何从 django 模板中的 for 循环中获取特定的 id?
【发布时间】:2021-07-27 03:09:26
【问题描述】:

我正在使用 django 和 javascript,我正在尝试在不刷新页面的情况下关注和取消关注多个用户。因此我使用ajax。我现在面临的问题是,无论我点击该用户还是其他用户,第一个关注者都会关注和取消关注。这是一个明显的行为,因为我不明白如何获取用户的特定 ID来自 for 循环,以便我可以在 js 函数中使用该用户。

               {% if follower.user in request.user.userprofile.follower.all %}
                 <span><a class="btn btn-success" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}UnFollow</a></span>
                 {% else %}
                
                 <span><a class="btn btn-warning" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}Follow</a></span>
                  {% endif %}
                </div><!--/ followers-body -->
                {% endfor %} 




<script>
    
        
        
        $(document).on('click','a[id^=follow-button]', function (e) {
            var user = $('#follow-button').attr('toggle'); //this user is coming the first use of looping object..no matter if i click on the 2nd or 3rd user of the loop.
            console.log(user,'im im im tested');
            e.preventDefault();
            $.ajax({
            type: 'POST',
            url: '{% url "profiles:toggle" %}',
            data: {
                user_toggle: user,
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                action: 'POST',
            },
            success: function (json) {
                result = json['result']
                console.log(result,"maii mai maima maima a")
                if (result) {
                    document.getElementById("is_following").innerHTML = '<a class="btn btn-success" id="follow-button" toggle="{{user.userprofile}}" type="submit">{% csrf_token %}UnFollow</a>'
                    }
                else
                    document.getElementById("is_following").innerHTML = '<a class="btn btn-warning" id="follow-button" toggle="{{user.userprofile}}" type="submit">{% csrf_token %}Follow</a>'
                    
            },
            error: function (xhr, errmsg, err) {
            }
            });
        })
</script>

【问题讨论】:

    标签: django django-rest-framework django-views django-forms django-templates


    【解决方案1】:

    这更多的是 JS/JQuery 问题而不是 Django 问题,但这是我认为您缺少的问题。

    向元素添加侦听器时,您可以选择使用保存的单词 this 获取与之交互的元素。

    您在代码中的问题是您检索user 的那一行。如果您将$('#follow-button') 替换为$(this),那么您将获得被点击的用户。
    从那里您可以轻松检索 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 2013-10-26
      • 2010-11-09
      相关资源
      最近更新 更多