Home > database >  sqlalchemy.exc.ArgumentError
sqlalchemy.exc.ArgumentError

Time:08-04

For some reason I get this error: Traceback (most recent call last): File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 2091, in call return self.wsgi_app(environ, start_response) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 2076, in wsgi_app response = self.handle_exception(e) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app response = self.full_dispatch_request() File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 1519, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 1517, in full_dispatch_request rv = self.dispatch_request() File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/flask/app.py", line 1503, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/Users/stackoverflow/code/FlaskTaskr/project/views.py", line 23, in wrap return test(*args, **kwargs) File "/Users/stackoverflow/code/FlaskTaskr/project/views.py", line 87, in tasks closed_tasks=closed_tasks() File "/Users/stackoverflow/code/FlaskTaskr/project/views.py", line 33, in closed_tasks return db.session.query(Task).filter_by(status='0').order_by(Task.due_date.asc) File "", line 2, in order_by File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/base.py", line 110, in _generative x = fn(self, *args, **kw) File "", line 2, in order_by File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/orm/base.py", line 230, in generate fn(self, *args[1:], **kw) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 1839, in order_by criterion = tuple( File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 1840, in coercions.expect(roles.OrderByRole, clause) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/coercions.py", line 129, in expect return lambdas.LambdaElement( File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/lambdas.py", line 163, in init rec = self._retrieve_tracker_rec(fn, apply_propagate_attrs, opts) File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/lambdas.py", line 179, in _retrieve_tracker_rec tracker = AnalyzedCode.get( File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/lambdas.py", line 632, in get cls._fns[fn.code] = analyzed = AnalyzedCode( File "/Users/stackoverflow/code/FlaskTaskr/.venv/lib/python3.8/site-packages/sqlalchemy/sql/lambdas.py", line 639, in init raise exc.ArgumentError( sqlalchemy.exc.ArgumentError: Method <bound method ColumnOperators.asc of <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x105b678b0>> may not be passed as a SQL expression sqlalchemy.exc.ArgumentError: Method <bound method ColumnOperators.asc of <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x10403e810>> may not be passed as a SQL expression but for the life of me I can't figure out why. I expect my web application to login and show the tasks. but it returns that error message. Here is my views.py:

    from forms import AddTaskForm, RegisterForm, LoginForm

    import datetime
    from functools import wraps
    from flask import Flask, flash, redirect, render_template, \
        request, session, url_for
    from flask_sqlalchemy import SQLAlchemy

    app = Flask(__name__)
    app.config.from_object('_config')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    db = SQLAlchemy(app)

    from models import Task, User


    def login_required(test):
        @wraps(test)
        def wrap(*args, **kwargs):
            if 'logged_in' in session:
                return test(*args, **kwargs)
            else:
                flash('You need to login first.')
                return redirect(url_for('login'))
        return wrap

    def open_tasks():
        return db.session.query(Task).filter_by(status='1').order_by(Task.due_date.asc())

    def closed_tasks():
        return db.session.query(Task).filter_by(status='0').order_by(Task.due_date.asc)


    @app.route('/logout/')
    def logout():
        session.pop('logged_in', None)
        session.pop('user_id', None)
        flash('Goodbye!')
        return redirect(url_for('login'))


    @app.route('/', methods=['GET', 'POST'])
    def login():
        error = None
        form = LoginForm(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                user = User.query.filter_by(name=request.form['name']).first()
                if user is not None and user.password == request.form['password']:
                session['logged_in'] = True
                session['user_id'] = user.id
                flash('Welcome!')
                return redirect(url_for('tasks'))
                else:
                    error = 'Invalid username or password.'
            else:
                error = 'Both fields are required.'
        return render_template('login.html', form=form, error=error)


    @app.route('/register/', methods=['GET', 'POST'])
    def register():
        error = None
        form = RegisterForm(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                new_user = User(
                    form.name.data,
                    form.email.data,
                    form.password.data,
                )
                db.session.add(new_user)
                db.session.commit()
                flash('Thanks for registering. Please login.')
                return redirect(url_for('login'))
        return render_template('register.html', form=form, error=error)


    @app.route('/tasks/')
    @login_required
    def tasks():
        return render_template('tasks.html', 
        form=AddTaskForm(request.form),
        open_tasks=open_tasks(),
        closed_tasks=closed_tasks()
        )


    @app.route('/add/', methods=['GET', 'POST'])
    @login_required
    def new_tasks():
        error = None
        form = AddTaskForm(request.form)
        if request.method == 'POST':
            if form.validate_on_submit():
                new_task = Task(
                    form.name.data,
                    form.due_date.data,
                    form.priority.data,
                    datetime.datetime.utcnow(),
                    '1',
                    session['user_id']
                )
                db.session.add(new_task)
                db.session.commit()
                flash('New entry was successfully posted. Thanks.')
                return redirect(url_for('tasks'))
        return render_template(
            'tasks.html',
            form=form,
            error=error,
            open_tasks=open_tasks(),
            closed_tasks=closed_tasks
        )

    @app.route('/complete/<int:task_id>/')
    @login_required
    def complete(task_id):
        new_id = task_id
        db.session.query(Task).filter_by(task_id=new_id).update({"status": "0"})
        db.session.commit()
        flash('The task is complete. Nice.')
        return redirect(url_for('tasks'))


    @app.route('/delete/<int:task_id>/')
    @login_required
    def delete_entry(task_id):
        new_id = task_id
        db.session.query(Task).filter_by(task_id=new_id).delete()
        db.session.commit()
        flash('The task was deleted. Why not add a new one?')
        return redirect(url_for('tasks'))

This is my models.py:

    from views import db

    import datetime


    class Task(db.Model):

        __tablename__ = "tasks"

        task_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String, nullable=False)
        due_date = db.Column(db.Date, nullable=False)
        priority = db.Column(db.Integer, nullable=False)
        posted_date = db.Column(db.Date, default=datetime.datetime.utcnow())
        status = db.Column(db.Integer)
        user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

        def __init__(self, name, due_date, priority, posted_date, status, user_id):
            self.name = name
            self.due_date = due_date
            self.priority = priority
            self.posted_date = posted_date
            self.status = status
            self.user_id = user_id

        def __repr__(self):
            return '<name {0}>'.format(self.name)


    class User(db.Model):

        __tablename__ = 'users'

        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String, unique=True, nullable=False)
        email = db.Column(db.String, unique=True, nullable=False)
        password = db.Column(db.String, nullable=False)
        tasks = db.relationship('Task', backref='poster')

        def __init__(self, name=None, email=None, password=None):
            self.name = name
            self.email = email
            self.password = password

        def __repr__(self):
            return '<User {0}>'.format(self.name) 

This is my forms.py:

    # project/forms.py


    from flask_wtf import FlaskForm
    from wtforms import StringField, DateField, IntegerField, \
        SelectField, PasswordField
    from wtforms.validators import DataRequired, Length, EqualTo, Email


    class AddTaskForm(FlaskForm):
        task_id = IntegerField()
        name = StringField('Task Name', validators=[DataRequired()])
        due_date = DateField(
            'Date Due (mm/dd/yyyy)',
            validators=[DataRequired()], format='%Y-%m-%d'
        )
        priority = SelectField(
            'Priority',
            validators=[DataRequired()],
            choices=[
                ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'),
                ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10')
            ]
        )
        status = IntegerField('Status')


    class RegisterForm(FlaskForm):
        name = StringField(
            'Username',
            validators=[DataRequired(), Length(min=6, max=25)]
        )
        email = StringField(
            'Email',
            validators=[DataRequired(), Email(), Length(min=6, max=40)]
        )
        password = PasswordField(
            'Password',
            validators=[DataRequired(), Length(min=6, max=40)])
        confirm = PasswordField(
            'Repeat Password',
            validators=[DataRequired(), EqualTo('password')]
        )


    class LoginForm(FlaskForm):
        name = StringField(
            'Username',
            validators=[DataRequired()]
        )
        password = PasswordField(
            'Password',validators=[DataRequired()])

Thank you in advance.

CodePudding user response:

In the line in views.py:

def closed_tasks():
        return db.session.query(Task).filter_by(status='0').order_by(Task.due_date.asc)

I think you're missing brackets after the order_by call should be .asc() not just .asc:

  • Related