nx_prv
nx_prv

Reputation: 127

Why is the render_template not being expressed?

I have a working flask app set up with a HTML page. The problem is that in my HTML, where I have {{ Appointments }}, it always shows the value of the second render_template, of an empty list.

@app.route("/PatientDashboard.html", methods=["GET", "POST"])
def PatientDashboard():

    if request.method == "POST":
        Date = request.form.get("Date")
        print(Date)
        return render_template("PatientDashboard.html", Appointments=["This should show up."])

    else:
        return render_template("PatientDashboard.html", Appointments=[]) 

The problem is that the first render_template is never expressed. Why is this and how would I solve it?

Thank you ever so much in advance.

EDIT 1:

Relevant HTML is below.

<script>
    var jsDate = $('#calendar').datepicker({
        inline: true,
        firstDay: 1,
        showOtherMonths: false,
        dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        onSelect: function(dateText, inst) {
            document.getElementById("Date").innerHTML = dateText;
            $.ajax({
                type: 'POST',
                url: "{{ url_for('PatientDashboard') }}",
                data: {Date: dateText},
                dataType: "text",
            });
        }
    });
</script>

Further on I have the {{ Appointments }} in a divider.

Upvotes: 0

Views: 64

Answers (1)

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28474

You are getting the content of rendered template with Appointments into a response of your POST request. If you want to use Appointments data on your page, you need to extend your POST request with a callback which will use that data for whatever you need.

So basically what happens:

  1. Page loads (GET request), template is rendered with an empty Appointments list
  2. Page fires POST ajax request, which returns rendered template with Appointments set
  3. You are not processing POST response, hence this data is just discarded.

Typical approach is to obtain only relevant data (for example, in JSON format) from POST response, not a full page:

from flask import Response

if request.method == "POST":
    Date = request.form.get("Date")
    print(Date)
    Appointments=["This should show up."]
    return Response(json.dumps(Appointments), mimetype='application/json')
else:
    return render_template("PatientDashboard.html", Appointments=[]) 

Upvotes: 1

Related Questions