无法为POST和GET呈现不同的HTML模板[重复]

qcuzuvrc  于 2023-01-24  发布在  其他
关注(0)|答案(1)|浏览(158)
    • 此问题在此处已有答案**:

How to render Django template after ajax call(1个答案)
4天前关闭。
我想为相同路由的GET和POST请求呈现不同的HTML模板。提交表单后(在GET中)我为POST请求编写的代码可以工作,但是它不能呈现模板(返回值)。实际上,页面甚至都没有加载我不I don "我不知道这是否与我如何编写表单提交按钮的JavaScript有关,因为其他一切似乎都是它应该做的。这段代码的目的是随机化电影/元素的列表,如果它们适合放置的标签(制作于X年和Y年之间,是喜剧还是戏剧,等等)。第二个HTML只应该以随机顺序显示电影。

    • 应用程序. py代码**
@app.route("/randomizer", methods=["GET", "POST"])
def randomizer():

   # POST
   if request.method == "POST":

       # Recieve and print data
       form_data = request.get_json()

       # Movie status from form
       status = form_data['status']

       # List of genres checked in form
       form_genres = form_data['genres']

       # Initialize list for movies that pass the genre tag
       mlist2 = []

       # Initialize a list for the final movies to be randomized
       final_movies = []

       # Get release year from data
       ry = form_data['year']

       # Turn blank inputs into
       lower = int(ry[0] or lower_limit)
       upper = int(ry[1] or upper_limit)

       " MOVIE STATUS "
       # Listdict of all movies with that status (without tags applied)
       if status == 'unseen':
           mlist1 = db.execute("SELECT * FROM movies WHERE status = ? AND user_id = ?", 0, session['user_id'])
       elif status == 'seen':
           mlist1 = db.execute("SELECT * FROM movies WHERE status = ? AND user_id = ?", 1, session['user_id'])
       else:
           mlist1 = db.execute("SELECT * FROM movies WHERE user_id = ?", session['user_id'])

       " GENRES "
       # If any genre was clicked, rather than 'All Genres', query for genres
       if form_genres[0] != 'All Genres':

           # Loop through movies
           for movie in mlist1:

               # Loop through genres
               for g in form_genres:

                   # Check for genre in movie
                   passed = db.execute("SELECT * FROM genres WHERE movie_id = ? AND genre = ?", movie['id'], g)

                   # If passed is not blank (movie is from genre)
                   if passed:

                       # Only add movie if it is not already in the list
                       if movie not in mlist2:

                           # Add movie to final list
                           mlist2.append(movie)

       # If all genres want to be randomized, the list will be the same
       else:
           mlist2 = mlist1

       " RELEASE YEAR "
       # Loop through movies only if a limit was given
       if not (lower == lower_limit and upper == upper_limit):
           # Loop through movies
           for m in mlist2:
               # Get release year of movie
               my = db.execute("SELECT year FROM movies WHERE id = ?", m['id'])
               movie_year = my[0]['year']

               # None values for year don't pass if statement
               if movie_year:

                   # Check
                   if lower <= int(movie_year) <= upper:
                       final_movies.append(m)

       # Else the list will be the same as before
       else:
           final_movies = mlist2

       # Shuffle final list to finally randomize
       random.shuffle(final_movies)

       return render_template("randomizer2.html", movies=final_movies)

   # GET
   else:

       return render_template("randomizer1.html", genres=userGenres(session['user_id']))
    • 随机数发生器1.html**
{% extends "layout.html" %}

{% block title %}
    Randomizer
{% endblock %}

{% block main %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    function genreChecked(element) {
        // Unclick genres if all-genres is clicked and vice versa
        var allGenres = document.getElementById('all-genres');
        var genres = document.getElementsByName('cbox-genre');

        // Check if all-genres clicked
        if (element.id == 'all-genres') {
            // Uncheck all other genres
            for (var i = 0; i < genres.length; i++) {
                genres[i].checked = false;
            }
        }

        // If any other genre is clicked, unclick all-genres
        else {
            allGenres.checked = false;
        }
    }

    function testing() {

        // All radio
        let radios = document.getElementsByName('radio-seen');
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
                var checkedRadio = radios[i].value;
            }
        }

        // All cbox genres
        let genres = document.querySelectorAll(".cbox-genre");
        let checkedGenres = [];
        for (var i = 0; i < genres.length; i++) {
            if (genres[i].checked) {
                checkedGenres.push(genres[i].value)
            }
        }

        // Release Year
        let releaseFrom = document.getElementById('from')
        let releaseTo = document.getElementById('to')
        console.log(typeof(releaseFrom))
        let releaseYear = [releaseFrom.value, releaseTo.value]

        // AJAX code
        $.ajax({
            url: "/randomizer",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                status: checkedRadio,
                genres: checkedGenres,
                year: releaseYear
            }),
        })
    }
</script>
 <div class="tags">
    <form action="/randomizer" method="post">
        <div class="tag" id="movieStatus-tag">
            <div class="header">Watched or not</div>
            <div class="body">
                <!-- Allow only one to be checked -->
                <input type="radio" id="all" name="radio-seen" value="all">
                <label for="all">All Movies</label>
                <input type="radio" id="unseen" name="radio-seen" value="unseen">
                <label for="unseen">Unseen</label>
                <input type="radio" id="seen" name="radio-seen" value="seen">
                <label for="seen">Seen</label>
            </div>
        </div>
        <div class="tag" id="genre-tag">
            <div class="header">Genres</div>
            <div class="body">
                <li>
                    <input type="checkbox" id="all-genres" class="cbox-genre" name="cbox-all-genres" value="All Genres" onclick="genreChecked(this)">
                    <label for="all-genres">All Genres</label>
                </li>
                {% for genre in genres %}
                    <li>
                        <input type="checkbox" id="{{ genre }}" class="cbox-genre" name="cbox-genre" value="{{ genre }}" onclick="genreChecked(this)">
                        <label for="{{ genre }}">{{ genre }}</label>
                    </li>
                {% endfor %}
            </div>
        </div>
        <div class="tag" id="year-tag">
            <div class="header">Release Year</div>
            <div class="body">
                <!-- From, to. -->
                <input type="text" id="from" placeholder="From">
                <input type="text" id="to" placeholder="To">
            </div>
        </div>
        <div class="submit-tags">
            <input type="button" onclick="testing()"/>
        </div>
    </form>
 </div>
{% endblock %}
    • 随机数发生器2.html**
{% extends "layout.html" %}

{% block title %}
    Randomizer
{% endblock %}

{% block main %}
    <h3>Randomized List</h3>
    <ol>
        {% for movie in movies %}
            <li>{{ movie['title'] }}</li>
        {% endfor %}
    </ol>
{% endblock %}
iswrvxsc

iswrvxsc1#

所以问题在于你是如何提交表单的,因为你使用 AJAX 来提交表单,所以post中的“return render”不会像ajax请求那样工作,因为ajax请求期望返回一个json响应,并且不会触发return render。如果你想在表单提交后呈现一个模板,而不需要重定向,那么你需要以默认方式提交表单,并且不要使用ajax或Javascript方法来提交表单。
如果你想使用 AJAX ,那么你可以创建新的元素来加载页面上的不同数据,更多细节请看question

相关问题