Albert
Albert

Reputation: 19

TypeError at /book/2 string indices must be integers

I'm new to Django, I have encountered this error

TypeError at /book/1 string indices must be integers

I have a JSON file called book.json (seen below)

{
    "books":[
        {
          "id": 1,
          "title": "Unlocking Android",
          "isbn": "1933988673",
          "status": "PUBLISH",
          
        },
        .....

I'm trying to get single book using id in the view

def show(request, id):
    with open('bookstore/books.json') as file:
        books = json.load(file)

    book = [book for book in books if book['id'] == id]

    return render(request, 'books/show.html', book)

The index.html template has this code

{% for book in books  %}
    <a href="/book/{{book.id}}"></a>       
 {% endfor %}

for book links

Upvotes: 1

Views: 72

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477328

You should pass the books in the context, and access the books key in the JSON blob:

def show(request, id):
    with open('bookstore/books.json') as file:
        books = json.load(file)['books']
    books = [book for book in books if book['id'] == id]

    return render(request, 'books/show.html', {'books': books})

Upvotes: 1

Henty
Henty

Reputation: 603

try

book_dict = json.load(file)
book = [book for book in book_dict['books'] if book['id'] == id]

as it looks like you aren't doing the first step into the json

Upvotes: 1

Related Questions