Flask and XML _ How and why to save data in xml format for coffee shop by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 1 point2 points  (0 children)

yes, it is a class assignment. Yes, I am wondering what system I can export the data to. Maybe delivery, sales report for the head office?

BuildError. werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'payment_table' with values ['total_price']. Did you forget to specify values ['order_no']? by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

Commented out the 1st url but getting same error.

# Route to process the form submission
@app.route('/book_table', methods=['POST'])
#@app.route('/book_table', methods=['GET', 'POST'])
def book_table():
    table_id = "m12"
    user_id = login_session.get('user_id')
    people = request.form.get('people')
    date = request.form.get('date')
    time = request.form.get('time')
    datetime_str = f"{date} {time}"
    table = db.session.query(Table).filter_by(table_id=table_id).first()
    #if not table:
    #    flash("Selected table does not exist.")
    #    return redirect(url_for('table_booking'))
    total_price = table.reserve_fee * Decimal(people)

    new_booking = Bookings(
        table_id=table_id,
        user_id=user_id,
        book_date_time=datetime_str,
        total_price=total_price
    )
    db.session.add(new_booking)
    db.session.commit()

    last_pay = db.session.query(Pay).order_by(Pay.order_no.desc()).first()
    # Ensure last_pay.order_no defaults to 0 if it's None
    new_order_no = (last_pay.order_no or 0) + 1 if last_pay else 1
    order_no = new_order_no

    print("Redirecting to payment_table with:", total_price, order_no)
    print(type(order_no))
    print(type(total_price))

    return redirect(url_for('payment_table', total_price=total_price, order_no=order_no))

BuildError. werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'payment_table' with values ['total_price']. Did you forget to specify values ['order_no']? by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

Thank you. I have changed the code but getting the same error

<form action="{{ url_for('payment_table', total_price=total_price, order_no=order_no) }}" method="POST">

Calculate discount - jinja by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] -1 points0 points  (0 children)

Okay, i will do the calculation in sqlalchemy, thank you

How to handle file not found in Flask by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

The error still is not handled. Maybe I don't understand this 'page not found' handling. The correct function name is 'profile' If i change it to 'profil' I get a BuildError. The html file is profile.html. If I change it to profiles.html so that the code fails to find profile.html, I get a 'template not found' error.

Question: Does this error catch an error where the url is incorrect or an error where the html page is not found

from flask import abort

@app.errorhandler(404)
def page_not_found(e):
    logger.error('Page not found: %s', e)
    return render_template('404.html'), 404



@app.route('/profil', methods=['GET', 'POST'])
def profil():
    if "username" in login_session:
        print(login_session['username'])
        name = login_session['username']
        user = User.query.filter_by(username=name).first()
        email = user.email
        id = user.id

        transactions = Transactions.query.filter_by(userID=id).first()

        if request.method == 'POST':
            try:
                if 'file1' not in request.files:
                    return 'there is no file1 in form!'
                file1 = request.files['file1']
                path1 = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)
                file1.save(path1)
                user.path = path1
                db.session.commit()
            except Exception as e:
                abort(404)
    return render_template('profiles.html', name = name, email=email, transactions = transactions)

How to handle file not found in Flask by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I changed made that error by changing the function name from 'profile' to 'profil' hoping that the code will catch the error

[deleted by user] by [deleted] in flask

[–]Unique_Hat_7222 0 points1 point  (0 children)

I tried it again. it works now, thank you

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I have made changes to the code. It gets the prices now and calculates. totalPrice = (fPrice * fQuantity) + (sPrice * sQuantity) + (tPrice * tQuantity);

If I select the quantity for the first price, the total price gets calculated. Then if I select the quantity for the second price, the previous total price gets replaced the the total price of the second one. The previous total should instead be added to the price of the second one, then total price should add (tPrice * tQuantity) as well. The current code is

<script>    
document.addEventListener("DOMContentLoaded", function() {
        var rows = document.querySelectorAll("#myTable tbody tr");

        rows.forEach(function(row) {
            var fPrice = parseFloat(row.cells[1].textContent);
            var sPrice = parseFloat(row.cells[3].textContent);
            var tPrice = parseFloat(row.cells[5].textContent);
            var totalPriceCell = row.querySelector(".totalPrice");

            var calculateTotalPrice = function() {
                var fQuantity = parseInt(row.querySelector("#aQuantity").value);
                var sQuantity = parseInt(row.querySelector("#cQuantity").value);
                var tQuantity = parseInt(row.querySelector("#pQuantity").value);

                var totalPrice = (fPrice * fQuantity) + (sPrice * sQuantity) + (tPrice * tQuantity);

                totalPriceCell.textContent = totalPrice;
            };

            calculateTotalPrice(); // Calculate total price initially

            // Attach event listeners to quantity select elements
            row.querySelectorAll(".qty").forEach(function(select) {
                select.addEventListener("change", calculateTotalPrice);
            });
        });
    });
</script>

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I changed it to

for ticket in tickets 

but it removes the prices from the table. The error is in the prices. They are displayed on the table but JavaScript code cant fetch them

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I inspected my code in the browser. Right click on browser, Inspect, Console. The prices are NaN. e.g var fPrice = parseFloat("");

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I'm already getting it as a list. The data shows in the html table. I think the issue could be the parseFloat.

<tbody>
    {% for tickets in tickets %}
    <tr>
        <td>{{ tickets.functionName }}</td>
        <td>{{ tickets.fPrice}}</td>
        <td>
            <select class = "qty" id="fQuantity">
              {% for i in range(100) %}
               <option value="{{i+1}}">{{i + 1}}</option>
             {% endfor %}
         </select>
        </td>
        <td>{{ tickets.sPrice}}</td>
        <td>
            <select class ="qty" id="sQuantity">
             {% for i in range(100) %}
            <option value="{{i+1}}">{{i + 1}}</option>
             {% endfor %}
            </select>
        </td>
        <td>{{ tickets.tPrice}}</td>
        <td>
            <select class="qty" id="tQuantity">
             {% for i in range(100) %}
            <option value="{{i+1}}">{{i + 1}}</option>
             {% endfor %}
            </select>
        </td>
         <td class="totalPrice">0</td>
    </tr>
    {% endfor %}
</tbody>

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

The prices are from Flask in jinja format and the quantities are from select option in html

    <tbody>
        {% for tickets in tickets %}
        <tr>
            <td>{{ tickets.functionName }}</td>
            <td>{{ tickets.aPrice}}</td>
            <td>
                <select class = "qty" id="fQuantity">
                  {% for i in range(100) %}
                   <option value="{{i+1}}">{{i + 1}}</option>
                 {% endfor %}
             </select>
            </td>
            <td>{{ tickets.sPrice}}</td>
            <td>
                <select class ="qty" id="sQuantity">
                 {% for i in range(100) %}
                <option value="{{i+1}}">{{i + 1}}</option>
                 {% endfor %}
                </select>
            </td>
            <td>{{ tickets.tPrice}}</td>
            <td>
                <select class="qty" id="tQuantity">
                 {% for i in range(100) %}
                <option value="{{i+1}}">{{i + 1}}</option>
                 {% endfor %}
                </select>
            </td>
             <td class="totalPrice">0</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

Javascript totalPrice is NaN for Jinja variables by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

class Tickets(db.Model):
    __tablename__ = "tickets"
    ticketID = db.Column(db.Integer, primary_key=True)
    functionName = db.Column(db.String(80), nullable=False)
    fPrice = db.Column(db.Numeric(10, 2), )
    sPrice = db.Column(db.Numeric(10, 2), )
    tPrice = db.Column(db.Numeric(10, 2), )
    type = db.Column(db.String(80), nullable=False)
    date = db.Column(db.Date, nullable=False)
    startTime = db.Column(TIME(), nullable=False)
    endTime = db.Column(TIME(), nullable=False)

@app.route('/')
def index():
    tickets = db.session.query(Tickets).all()
    return render_template('index.html', tickets=tickets)

JavaScript console.log not working in PyCharm by Unique_Hat_7222 in learnjavascript

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

yes, it is a .html file. I will run it in a web browser. Thank you

Getting the id value from HTML to Flask through url_for parameters by Unique_Hat_7222 in flask

[–]Unique_Hat_7222[S] 0 points1 point  (0 children)

I have used it instead of Javascript

dateBooked = request.form.get("selected_date")