pythonsqlalchemyflask-sqlalchemy

Flask. add() takes from 2 to 3 positional arguments but 4 were given


I'm a student creating a simple wish-list website that uses user-entered data through Flask and SQLAlchemy. I've been struggling with this issue and many others ever since I added some new columns to my database. The user inputs the fields through the following HTML form:

<form action="{{url_for('add')}}" method='POST'>
    <input type="text" name="content" id="content">
    <input type="text" name="link" id="link">
    <input type="text" name="price" id="price">
    <input type="submit" value="Add Item">
</form>

When the user presses the submit button, it runs the below code to add the user-inputted fields into my database, content, price, and link. But whatever I do, it doesn't commit to my database, and when it nearly does, it simply throws all of the user inputs into the content column in my database, then throws an error (which is probably caused by my attempted workarounds of this problem)

@app.route("/add", methods=["GET", "POST"])
def add():
    if request.method == 'POST':
        item_content = request.form['content']
        item_price = request.form['price']
        item_link = request.form['link']

        try:             #Try to add new item and if fail return error message
            db.session.add(item_content, item_price, item_link) #add the column/row in db
            db.session.commit() #commit item to datebase
        return redirect('/index') #go back to main page
        except:
            return 'There was an Issue adding this item'

Many Thanks!


Solution

  • Fixed my issue with some help from a friend.

    @app.route("/add", methods=["GET", "POST"])
    def add():
        if request.method == 'POST':
            item_content = request.form.get('content')
            item_price = request.form.get('price')
            item_link = request.form.get('link')
    
            try:
                finalentry = wl(content = item_content, price = item_price , link = item_link) 
                db.session.add(finalentry) 
                db.session.commit()
                return redirect('/index') 
            except:
                return 'There was an Issue adding this item'
    

    I fixed the issue by only adding a combined variable to the db.session.add instead of just adding them all as seperate variables. Not quite sure how this fixed my problem but I'll take the win. :>