compare two results (of many) from api data with django/python
<p>I'm learning django/python/css/etc... and while doing this, I've decided to build an app for my website that can pull simple movie data from TMDb. What I'm having trouble with is figuring out a way to add a way for the <strong>user to select two different movies, and once selected, see the differences between them (run time, budget, etc).</strong></p>

<p>I've got grabbing the data from the API covered in that doing a search for a movie on my site returns expected results. But now I'm having a really tough time trying to figure out <strong>how to select 1 item from the results to "save" it, search again, select the second movie, and have the comparison show up.</strong></p>

<p>I know it's pretty vague, but any help getting me pointed in the right direction would be greatly appreciated!</p>

<p>here's what I'm doing so far with the code:</p>

<p>views.py:</p>

<pre><code>from django.shortcuts import render
from django.conf import settings

from .forms import MovieSearch
import tmdbsimple as tmdb

tmdb.API_KEY = settings.TMDB_API_KEY


def search_movie(request):
    """
    Search movie title and return 5 pages of results
    """
    parsed_data = {'results': []}
    if request.method == 'POST':
        form = MovieSearch(request.POST)
        if form.is_valid():
            search = tmdb.Search()
            query = form.cleaned_data['moviename']
            response = search.movie(query=query)
            for movie in response['results']:
                parsed_data['results'].append(
                    {
                        'title': movie['title'],
                        'id': movie['id'],
                        'poster_path': movie['poster_path'],
                        'release_date': movie['release_date'][:-6],
                        'popularity': movie['popularity'],
                        'overview': movie['overview']
                    }
                )
            for i in range(2, 5 + 1):
                response = search.movie(query=query, page=i)
                for movie in response['results']:
                    parsed_data['results'].append(
                        {
                            'title': movie['title'],
                            'id': movie['id'],
                            'poster_path': movie['poster_path'],
                            'release_date': movie['release_date'][:-6],
                            'popularity': movie['popularity'],
                            'overview': movie['overview']
                        }
                    )
            context = {
                "form": form,
                "parsed_data": parsed_data
            }
            return render(request, './moviecompare/movies.html', context)
        else:
            form = MovieSearch()
    else:
        form = MovieSearch()

    return render(request, './moviecompare/compare.html', {"form": form})


def get_movie(request, movid):
    """
    from search/movie results, get details by movie id (movid)
    """
    movie = tmdb.Movies(movid)
    response = movie.info()
    context = {
        'response': response
    }
    return render(request, './moviecompare/detail.html', context)
</code></pre>

<p>movies.html:</p>

<pre><code>{% extends 'moviecompare/compare.html' %}

{% block movies_returned %}
&lt;div class="wrap"&gt;
&lt;div class="compare-gallery"&gt;

{% for key in parsed_data.results|dictsortreversed:'release_date' %}
{% if key.poster_path and key.release_date and key.title and key.overview %}
    &lt;div class="gallery-item"&gt;
        &lt;img src="http://image.tmdb.org/t/p/w185/{{ key.poster_path }}"&gt;
   &lt;div class="gallery-text"&gt;
       &lt;div class="gallery-date"&gt;&lt;h5&gt;&lt;span&gt;&lt;i class="material-icons"&gt;date_range&lt;/i&gt;&lt;/span&gt; {{ key.release_date }}&lt;/h5&gt;&lt;/div&gt;
        &lt;div class="gallery-title"&gt;&lt;h3&gt;&lt;a href="{% url 'compare:movie_detail' movid=key.id %}"&gt;{{ key.title }}&lt;/a&gt;&lt;/h3&gt;&lt;/div&gt;
       &lt;div class="gallery-overview"&gt;{{ key.overview|truncatechars:80 }}&lt;/div&gt;
       &lt;/div&gt;
    &lt;/div&gt;
{% endif %}
{% endfor %}
&lt;/div&gt;
&lt;/div&gt;
{% endblock %}
</code></pre>

<p>and I've got a simple detail.html that doesn't do anything just yet, but it's just for showing detail results for a single movie, so not important to get into yet as it'll just be styling.</p>

<p>I'd like for each result in the gallery to have a link to a details page for the movie(done), and also a select box (or similar) to select it as one of the comparison movies.</p>

<p>If I can just get some help on how to select two different movies from the search results, and compare those, I think I could work out a way to do the same with two separate movie searches. Thanks for any help!</p>

<p>edit: here's what I have so far on <a href="http://moniblog.pythonanywhere.com/compare/" rel="nofollow">pythonanywhere</a> - </p>

<p>Assuming you want to be able to add movies from different searches (e.g. search for rambo, add rambo, search for south park, add south park), you can probably do something like:</p>

<pre><code>@require_POST
def save_compare(request, pk):
     """ Async endpoint to add movies to comparison list """
     movies = request.session.get('comparing_moviews', [])
     movies.append(movies)

     # if you only need the data the API served originally, you could also save that to a data-base when you read it from the API and use it here
     request.session['comparing_movies'] = movies
     return JsonResponse("")

def show_comparison(request):
     """ show differing stats like "1 hour 3 mins longer """
     mov1, mov2 = request.session.get('comparing_movies')  # need to handle wrong number of selected

     # not sure from the description how to look up the movies by id
     mov1 = tmdb.Search().search(pk=mov1)
     mov2 = tmdb.Search().search(pk=mov2)

     return render_to_response("comparison.html", context={
          "mov1": mov1, "mov2": mov2, 
          "length_diff": mov1['length'] - mov2['length']})
</code></pre>

<p>to give you the comparison stats you want. You'll also need <a href="https://docs.djangoproject.com/en/1.10/topics/http/sessions/" rel="nofollow">session middleware</a> installed.</p>

<p>From the search results page, you'll add a button that triggers an async js post to <code>save_compare</code> which starts accumulating a comparison list. When they're done, they can click "compare" or something on that list, which will render "comparison.html" with the two movies and the diff however you like it.</p>

<p>As an example of some calculation for your "comparison.html", you can grab the hours and minutes from the <code>length_diff</code> and render them as "X hours and y minutes longer."</p>

javascript python html django