2

I am a Django novice attempting to build an app that allows users to add tracks to a playlist. I use sessions to generate a list of track id strings in a view and return an http response with the serialized array. The problem is that trying to iterate through the array in the template to build an ordered list does not format properly. It displays as a python list instead of the expected bulleted html list.

Any help would be greatly appreciated!

the Div

<!DOCTYPE html>

<div id="playlist">
<ol>
{% for track in playlist %}
    <li>{{track}}</li>
{% endfor %}
</ol>
</div>
</html>

the javascript

<script type="text/javascript">
    $(document).on('submit', '.track_form', function() {
        var $form = $(this);
            $.ajax({
                url: $form.attr('action'),
                data: $form.serialize(),
                type: $form.attr('method'),
                success: function (data) {

                    $("#playlist").html(data);
                },
                error: function(data) {
                    console.log('There was a problem');
                }
             });
             return false;    
         });
</script>

the view

def artistpage(request):
    if request.method == 'POST':
        session_playlist = request.session.get('session_playlist', [])
        tname = str(request.POST.get('track_name'))
        session_playlist.append(tname)
        request.session['session_playlist'] = session_playlist

        return HttpResponse(json.dumps(session_playlist))
4
  • But you're not iterating over the result returned from the Ajax call. You just dump it straight into the #playlist div. Commented Jul 30, 2017 at 18:38
  • How to iterate over the result? I suspected that was the problem but I am not sure how to approach the proper solution Commented Jul 30, 2017 at 18:45
  • Vivek has shown you one way to do it. Another is to change your view so that it renders a standalone template fragment, similar to the inner part of the HTML you have already, and returns that rather than JSON; then you can insert it into the HTML directly. Commented Jul 30, 2017 at 18:48
  • Interesting. So i would have two html files and insert one into the other? Commented Jul 30, 2017 at 18:50

1 Answer 1

4

Since you are using ajax call to make request, you need to create html list in javascript code. Django template will not work in this case. Once your ajax call returns success you can create list html like this.

<script type="text/javascript">
$(document).on('submit', '.track_form', function() {
    var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            data: $form.serialize(),
            type: $form.attr('method'),
            success: function (data) {
                var list_html = "<ol>";
                for( var i=0; i <data.length; i++) {
                   list_html += "<li>" + data[i] + "</li>";
                 }
                list_html += "</ol>"
                $("#playlist").html(list_html);
            },
            error: function(data) {
                console.log('There was a problem');
            }
         });
         return false;    
     });

Your html should look like this.

<!DOCTYPE html>
  <div id="playlist">
  </div>
</html>

So your view should look something like this.

def artistpage(request):
    if request.method == 'POST':
        session_playlist = request.session.get('session_playlist', [])
        tname = str(request.POST.get('track_name'))
        session_playlist.append(tname)
        request.session['session_playlist'] = session_playlist

       return HttpResponse(json.dumps(session_playlist), content_type="application/json")
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks Vivek! I will try this and report back
it works but it prints every character in the string as a new list item, instead of every string in the list. original ajax data looked like ['track1_id', 'track2_id', 'track3_id']
can you paste data that you received in ajax response here ?
probably you replace this data.session_playlist.length by data.length and data.session_playlist[i] by data[i] then it should work fine.
the data returns as ["Life Round Here", "Pembroke"] and will add another track each time a user presses submit on one of the forms
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.