Bashton
Bashton

Reputation: 339

Using TMDb API in Django Web Framework to retrieve posters for movies in a database

I'm displaying all movies in the database, in a list and would like to have the respective poster under each movie. I think I've made a mistake in my view, as I'm trying to make the request in a view class. The movie model has a 'tmdb' field, which stores the TMDb ID for each film.

It would be great if someone could point me in the right direction, for I'm still new to Django, and I've not used many APIs before.

I can't post a screenshot, but the resulting web page has an empty thumbnail under each movie listed.

Thank you in advance!

views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
import csv, io, requests
from .models import Movie
from django.views.generic import ListView
from . import config

my_api_key = 'my_api_key'
base_url = 'https://api.themoviedb.org/3/'

def index(request):
    return HttpResponse("Hello, world. This is the movie app index.")

class movie_list_view(ListView):
    model = Movie
    template_name = 'movieapp/movies.html'
    context_object_name = 'movies'
    ordering = ['movie_id']
    paginate_by = 100

    def movie_poster(request, movie_id):
        url = f'{base_url}movie/{Movie.tmdb}?api_key={my_api_key}&language=en-US&page=1'
        response = requests.get(url)
        tmdb_movies = {'movieposter':response.json()}
        return render(request, 'movies.html', context=tmdb_movies)

movies.html

{% block content %}

<h1>Movies</h1>

{% for movie in movies %}
<div>
    <h3> {{movie.title }}</h3>
    <img src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/{{movieposter.poster_path}}">
</div>
{% endfor %}

{% endblock content %}

models.py

from django.db import models

class Movie(models.Model):
    movie_id = models.IntegerField()
    title = models.CharField(max_length=200)
    genres = models.CharField(max_length=150)
    imdb = models.CharField(max_length=50)
    tmdb = models.CharField(max_length = 50)

    class Meta:
        ordering = ['movie_id']

    def __str__(self):
        return self.title

Upvotes: 1

Views: 1238

Answers (1)

Anjan Dhungana
Anjan Dhungana

Reputation: 1

May be add .jpg after {{movieposter.poster_path}} at image source in template.

Upvotes: 0

Related Questions