Django AJAX: Errors When Trying To Pass A List In POST Request

I am trying to pass a list to the view so that i can filter by that list. i have taken some ideas from another Stack Overflow question here which should be working but is giving me some errors.

attempt 1 shown below prints as an empty array []

attempt 2 shown below gives error the JSON object must be str, bytes or bytearray, not NoneType

the ajax code consol log error Array [1] so the list works there

EDIT: I know the error is that the data being passed is NoneType, which means that the list with the values inside isn't being passed through. I'm getting a error log from the AJAX call so there must be an error there. Can anyone point out where I'm wrong?

Here is the code

view

def find(request):

    Posts = Post.objects.all()

    genre_list = Genres.objects.all()

    if request.method == 'POST':

        #attempt 1
        genres_selected_use = request.POST.getlist('genres_selected') # this when printed shows an empty array []
    
        #attempt 2
        #genres_selected_use = json.loads(request.POST.get('genres_selected')) # this gives error *the JSON object must be str, bytes or bytearray, not NoneType*

        for arg in genres_selected_use:
            Posts = Posts.filter(genres=arg)
        print(genres_selected_use)
        #return redirect('find')

    context = {
        'products': Posts,
        'keyword_list': Keywords.objects.all(),
    }

    return render(request, 'find/find.html', context)

AJAX

$('.filter_form').submit(function(e){
    const url = $(this).attr('action')

    var genres_selected_initial = [];
            
    var genre_item = document.getElementById(`filter_idAction`);
    var genres_selected_id = $(genre_item).attr('value');
    var g = parseInt(genres_selected_id)

    if  (genre_item.classList.contains("clicked_filter")) {
        genres_selected_initial.push(g);
    }

    //var genres_selected = genres_selected_initial; //attempt 1
    
    var genres_selected = JSON.stringify(genres_selected_initial); //attempt 2

    $.ajax({
        type: 'POST',
        url: url,
        data: {
            'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
            'genres_selected': genres_selected,

                    
        },
        success: function(response){
            console.log(genres_selected)
        },
        error: function(response){
            console.log('error', genres_selected)
        }

    })

})

form

<form class="filter_form" action="{% url 'find' %}" method="POST">
    {% csrf_token %}
    #rest of form
</form>

I am guessing there is an easy fix for this?

2 answers

  • answered 2021-02-23 00:04 OtherBarry

    Try using request.POST.getlist('genres_selected', request.POST.getlist('genres_selected[]'))

    Sometimes the ajax field will append "[]" appended to the field name when it is given a list.

  • answered 2021-02-23 15:25 Humza

    For anyone with a similar problem

    it was solved by adding e.preventDefault()