1

I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

{% for id, poster in poster_id_zip %}
    <div style="display: inline-block; margin: 10px;" class="">
      <a href="{{ movie_details }}"><img src="{{ poster }}" alt=""></a>
      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>
    </div>
{% endfor %}

views.py

def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')

models.py

from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mesolaries
  • 298
  • 5
  • 14

3 Answers3

3

You don't need a ModelForm here. In the view that you post the form to just save the model in the database.

if request.method == "POST":
    MovieId.objects.update_or_create(movie_id=request.POST['movie-id'])
Asher
  • 677
  • 5
  • 10
0

I think all you have to do is create a ModelForm. And then do something like:

movie_form = MovieModelForm(request.POST)
if movie_form.is_valid():
    movie_form.save() # to save the object

Before that change the name of input item in HTML to this:

<input type="hidden" name="movie_id" value="{{ id }}">

to match the modelform.

rajkris
  • 1,775
  • 1
  • 9
  • 16
0

Maybe introduce some javascript to make an ajax call to another view which adds to the Movie model (I'm making an assumption you are just adding a record). If I were you, I'd change that model to:

class MovieLinkClick(models.Model):
    movie_id = models.IntegerField()

    def __str__(self):
        return self.movie_id

Change the link to:

<a href="{{ movie_details }}" data-movieid={{id}} class="movielink"><img src="{{ poster }}" alt=""></a>

then add some javascript in the template to watch for those clicks. If you've got jQuery loaded you can use the data attributes to easily get something like the movieid set in the a tag. (see https://api.jquery.com/data/). You'll likely also need a csrf_token if you are using a post method.

$(document).ready(function() {
  $('.movielink').on("click", function(e) {
    e.preventDefault();
    var link = $(this).attr("href");
    var id = $(this).data('movieid');
    $.ajax({
           url: "{% url 'movies:log_click' %}",
           type: "POST",
           data: {movie_id: id, csrfmiddlewaretoken: "{{ csrf_token }}" });
    window.location.href = link;  //redirect to the href 
  });
});

You'd need to create a suitable urls entry to handle the movies:log_click which accepts a post method. See https://docs.djangoproject.com/en/1.11/topics/http/urls/ for a refresher on that.

AMG
  • 1,606
  • 1
  • 14
  • 25
  • or put that class on the button instead of the link. On first read I thought you were trying to see if they were clicking on the movie link. – AMG Dec 05 '17 at 03:20