Home > database >  How do I send a django model to javascipt?
How do I send a django model to javascipt?

Time:07-22

How do I pass a django model to javascript? Specifically, I want to pass a django Movie model to javascript. In javascript, I would like to display the id something in the movie model at the time of score with an if statement.

def index(request):
    if Movie.objects.order_by('-stars').exists():
        movie = list(Movie.objects.order_by('-stars'))
    if TV.objects.order_by('-stars').exists():
        tv = TV.objects.order_by('-stars')
        print(tv)
    context = {
        'movie':movie,
    }
    return render(request, 'Movie/index.html',context)
fetchTrendingResults("all", "week")

        var mediaType = document.getElementById("media_type")
        mediaType.addEventListener("change", function(event) {
            fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day")
        })

        function fetchTrendingResults(media_type, time_window) {
            var trendingDiv = document.getElementById("trendings")
            trendingDiv.innerHTML = ""
            if (media_type == "score"){
                var js_list = {{movie}};
            }
            else{
            fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json"
                }}
                // todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。
                )
            .then(res => res.json())
            .then(data => {
                for (let i=0; i<data.results.length; i  ) {
                    var mainDiv = document.createElement("div");
                    mainDiv.setAttribute("class", "card");
                    mainDiv.setAttribute("style", "width: 18rem;");
                    var img = document.createElement("img");
                    img.setAttribute("src", "https://image.tmdb.org/t/p/w200"   data.results[i].poster_path);
                    img.setAttribute("class", "card-img-top");
                    img.setAttribute("alt", "...");
                    var body = document.createElement("div");
                    body.setAttribute("class", "card-body");
                    var title = document.createElement("h5");
                    title.setAttribute("class", "card-title");
                    if (data.results[i].name) {
                        title.innerHTML = data.results[i].name;
                    } else {
                        title.innerHTML = data.results[i].title;
                    }
                    //var text = document.createElement("p");
                    //text.setAttribute("class", "card-text");
                    //text.innerHTML = data.results[i].overview;
                    var link = document.createElement("a");
                    link.setAttribute("href", "/"   data.results[i].media_type   "/"   data.results[i].id   "/");
                    link.setAttribute("class", "btn btn-primary");
                    link.innerHTML = "View Details";
                    body.appendChild(title);
                    //body.appendChild(text);
                    body.appendChild(link);
                    mainDiv.appendChild(img);
                    mainDiv.appendChild(body);
                    document.getElementById("trendings").appendChild(mainDiv);
                }
            })
        }
        }

How do I pass a django model to javascript? Specifically, I want to pass a django Movie model to javascript. In javascript, I would like to display the id something in the movie model at the time of score with an if statement.

CodePudding user response:

You can send model data by just returning JsonResponse from the view (and for example creating JSON dict by forlooping QuerySet, or using model_to_dict Django built-in method) or by preserving your logic and sending html you need to override - even better - you can do both ways at the same time.

So, basically you write view like this:

from django.forms import model_to_dict
from django.http import Http404


def custom_ajax_view(request):
    if request.method != 'POST':
        raise Http404
    movies = Movie.objects.order_by('-stars')
    movie_dict = {}
    if movies.exists():
        movie_dict = {obj.id: model_to_dict(obj) for obj in movies}
    tv = TV.objects.order_by('-stars')
    tv_dict = {}
    if tv.exists():
        tv_dict = {obj.id: model_to_dict(obj) for obj in tv}
    context = {
        'movie': movie,
    }
    html = render_to_string(
        'Movie/index.html', context=context)
    return JsonResponse({
        'movies': movie_dict,
        'tvs': tv_dict,
        'html': html,
    })

And then you retrieve data via Ajax method (I prefer using jQuery for that) by writing:

$.ajax({
    url: CUSTOM_AJAX_URL,
    type: 'post',
    dataType: 'json',
    success: function (data) {
        // Here you retrieve your data and you can do something with it.
        console.log(data)
    }
});

You also can resolve your CUSTOM_AJAX_URL using template logic (post it at the end of template)

<script>
    const CUSTOM_AJAX_URL = "{% url 'custom_ajax_view' %}";
</script>
<script src="{% static 'your_script_name.js' %}"></script>

Then your script should see the CUSTOM_AJAX_URL (if you use script not directly by using inline method, but including script via script tag and placing it with static method in the code). If you place it directly, you can pass URL directly to the AJAX method.

  • Related