【问题标题】:How to get an element from list based on clicked link in Django Template?如何根据 Django 模板中的单击链接从列表中获取元素?
【发布时间】:2016-07-29 12:58:41
【问题描述】:

我正在创建私人消息应用程序,并以这种方式呈现我的消息:

return render(request,'mssg/mssg_page.html', {'inbox':inbox, 'current_mssg':current_mssg,})

收件箱包含所有邮件。当前消息是应该完全显示的消息。我在我的模板中列出了如下所示的消息列表:

{% for mssg in inbox %}
    <a href="#"><!-- here -->
       <div class="right">
          <h3>{{ mssg.mssg_from.username }} <small>{{ mssg.delivery_date }}</small></h3>
          <h2>{{ mssg.title|safe }}</h2>
          <p>{{ mssg.text|safe|truncatewords:15  }}</p>
       </div>
    </a>
{% endfor %}

我也在同一个模板中显示完整的当前消息。
我想在点击带有&lt;!-- here --&gt;commment 的链接后更改当前消息
我知道我可以发送消息 id 来查看、验证它并将其发送回模板。但它需要刷新页面。但是所有消息都已经在inbox 中列出的模板中,因此不需要刷新页面。我也知道可以从收件箱中选择这样的邮件{{inbox.0}}
但我不知道如何使它取决于点击的链接。我想它需要javascript。但即使我知道我可以通过在模板中放置inbox.0 来执行inbox[0] 之类的操作,我仍然不知道如何执行inbox[varriable] 之类的操作。
有什么办法吗?
如果不需要,我不希望我的页面刷新。
PS我正在使用bootsrap

【问题讨论】:

  • 我认为您应该使用 Ajax 调用来请求带有消息的视图,以便您可以验证这是对 的请求。 Ajax 调用将在不刷新页面的情况下为您获取数据,您可以在同一页面上显示结果。

标签: django django-templates django-bootstrap3


【解决方案1】:

使用 AJAX 将解决您的问题。请参阅this StackOverflow answer,其中解释了如何做到这一点:

$('a').click(function() { // This is a listener to the link you mentioned.
    $.ajax({
        url: '127.0.0.1:8000/your_ajax_url', // You will need to create a URL for your AJAX call.
        type: 'get', // This is the default though, you don't actually need to always mention it
        success: function(data) {
            alert(data);
        },
        failure: function(data) { 
            alert('Got an error dude');
        }
    }); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2017-11-14
    相关资源
    最近更新 更多