0
votes

I am trying to collect books in a shelf object. However when i try to add a book, the page does nothing and i get this error in my console "Uncaught (in promise) TypeError: Cannot read property 'push' of undefined". Need help with this.

main.js

function sendRequest(url,method,data) {
    var r = axios({
        method: method,
        url: url,
        data: data,
        xsrfCookieName: 'csrftoken',
        xsrfHeaderName: 'X-CSRFToken',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    return r
}

var app = new Vue({
    el : '#app',
    data:   {
        book: '',
        books:  [
            {title: 'one'},
            {title: 'two'}
        ]
    },
    
    created(){
        var vm = this;
        var r = sendRequest('','get')
            .then(function(response){
                vm.books = response.data.books; 

            })


    },
    methods: {
        createBook(){
            var vm = this;
            var formData = new FormData();
            formData.append('title', this.book);

            sendRequest('','post',formData)
                .then(function (response) {
                    vm.books.push(response.data.book); //PROBLEM HERE
                    vm.book = '';

                })
        }
    }

})

views.py

def add_book(request, shelf_id):
    context = {}
     if request.POST:
        shelf = get_object_or_404(Shelf, pk=shelf_id)
        book_form = BookCreation(request.POST)
        temp = book_form.save(commit=False)
        temp.shelf = shelf
        temp.save()
        if book_form.is_valid():
            books = book_form.save()
            return JsonResponse({'book': model_to_dict(books)},status=200)
    return render(request, 'shelf/addBook.html')

url.py

path('<int:shelf_id>/create_book', add_book, name='addbook'),
1
can you share json returned from request to that python backend?Davud Safarov
problem is probably here: vm.books = response.data.books;. where data.books is not array, but undefinedDavud Safarov
i ran console.log(response.data.song) in the sendRequest method and got {id: 9, title: "blah", shelf: 71, removed: false}. However the error keeps pointing to this line vm.books.push(response.data.book)B.obed

1 Answers

0
votes

Apparently the issue was with me using if request.POST instead of request.method =='POST' in my backend.

def add_book(request, shelf_id):
    context = {}
     if request.method == 'POST': //THIS IS WORKING CODE
        shelf = get_object_or_404(Shelf, pk=shelf_id)
        book_form = BookCreation(request.POST)
        temp = book_form.save(commit=False)
        temp.shelf = shelf
        temp.save()
        if book_form.is_valid():
            books = book_form.save()
            return JsonResponse({'book': model_to_dict(books)},status=200)
    return render(request, 'shelf/addBook.html')