Bug on the switch between months in python flask

  flask, flask-sqlalchemy, python

Bug on the switch between months

This code is executed. But it does not run properly and has bugs. Sometimes when I click on the "next" month, it goes until two months later, and sometimes it does not move and stays in the same month. The "previous" month key has the same problem.
Sometimes by clicking on the month "before" or "after", for example, 5 months go forward or backward or a few months go back or forward

The application is now available and you can see the problem for yourself: sendous.ir
What part of the code is the problem?

startDate = datetime.datetime.today()


@app.route('/', methods=['GET', 'POST'])
@register_breadcrumb(app, '.', 'Home')
def home():
    global startDate
    form = BuyForm()

    if request.method == 'POST':
        
        if request.form['submit_button'] == 'next':
            startDate = startDate + relativedelta(months=1, day=1)
            endDate = startDate + relativedelta(months=1, day=1)
            buys = Buy.query.filter(Buy.date >= startDate). 
                filter(Buy.date < endDate).all()

        elif request.form['submit_button'] == 'before':
            startDate = startDate + relativedelta(months=-1, day=1)
            endDate = startDate + relativedelta(months=1, day=1)
            buys = Buy.query.filter(Buy.date >= startDate). 
                filter(Buy.date < endDate).all()
 
        elif request.form['submit_button'] == 'current':
            startDate = datetime.datetime.today()
            endDate = startDate + relativedelta(months=1, day=1)
            buys = Buy.query.filter(Buy.date >= startDate). 
                filter(Buy.date < endDate).all()
    else:
        endDate = startDate + relativedelta(months=1, day=1)
        buys = Buy.query.filter(Buy.date >= startDate). 
            filter(Buy.date < endDate).all()
            
    return render_template('home.html',
                           form=form,
                           startDate=startDate.strftime('%Y/%m'),
                           buys=buys)

Source: Python Questions

LEAVE A COMMENT