简体   繁体   English

带有参数的django {%url%}(字典列表)

[英]django {% url %} with parameters (list of dicts)

I'm following the suggestion at: Refresh <div> element generated by a django template 我遵循以下建议: django模板生成的<div>元素刷新

I'm passing along a few variables, a la: 我传递了一些变量,例如:

url: '{% url 'search_results' 'sched_dep_local' flights|escapejs %}',

The problem is that 'flights' is a list of dicts that the search_results template needs access to, and it's pretty large and contains things like apostrophes 问题是“航班”是search_results模板需要访问的字典列表,它很大,并且包含撇号之类的内容

[{'foo': 'bar'}, {'foo': 'baz'}] and so on

So the only way I can use it with {% url %} appears to be with escapejs to get rid of the apostrophes, but then in views.py, I need it to be a list of dicts again, so I can do things like: 因此,我可以将其与{%url%}一起使用的唯一方法似乎是通过escapejs除去撇号,但是然后在views.py中,我需要将它再次作为字典列表,因此我可以做类似的事情:

def search_results(request, sort_key, flights):
    flights = search_utils.sort(flights, sort_key)
    return render_to_response('search_results.html', { 'flights' : flights} )                                                                                                                                    

Is there a simple way to do this? 有没有简单的方法可以做到这一点? Alternatively, am I going about this whole thing all wrong? 或者,我要把这整个事情都弄错吗?

ETA: See also (explains what I'm trying to do and why): 预计到达时间:另请参阅(解释我要做什么以及为什么这样做):

<script>
$(".sort").on("click", function() {
    $.ajax({
        url: '{% url 'search_results' 'sched_dep_local' flights|escapejs %}',
        success: function(data) {
            $('#search-results').html(data);
        }
    });
});
</script>

I have a template (in search_results.html) that prints some data for each flight in flights. 我有一个模板(在search_results.html中),该模板可为航班中的每个航班打印一些数据。 I want to sort that data and rerender the template, but I can't figure out how. 我想对这些数据进行排序并重新呈现模板,但是我不知道怎么做。

This isn't the right way to deal with complex data. 这不是处理复杂数据的正确方法。 Rather than sending it via the URL, you should be using a POST and sending it in the body of the request: since you're using jQuery, you can just do method: "POST" in that call. 您应该使用POST并在请求的正文中发送它,而不是通过URL发送它:由于您使用的是jQuery,因此您可以在该调用中执行method: "POST" In the backend, you can deserialize it from JSON. 在后端,您可以从JSON反序列化它。

However, it does seem a bit strange to do this at all; 但是,这样做似乎有点奇怪。 the data is evidently coming from the Django backend already, so it's not clear why you want to post it back there. 数据显然已经来自Django后端,因此尚不清楚为什么要将其发布到那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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