简体   繁体   中英

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

I'm following the suggestion at: Refresh <div> element generated by a django template

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

[{'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:

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. 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. In the backend, you can deserialize it from 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.

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