First of all I know what the problem is, But I dont know why or how to fix it, I know that the function needs to pass a string to the database, I have a view function for create and edit, in the create part I have added "str" to the function to over come the problem but I dont know how to do this for the edit part. The form has a querySelectField which is correctly populated for the create part, and when I submit the "str" transforms the query result correctly.

So to over come the problem I have added "str" to the create part of the function, but I cannot see how to add this to the edit part with the 'populate.obj', also I expect the field to be populated with the data stored in the db when I created the form, but it is not. It is only this QuerySelectfield which is causing the problems. Here is some of my code.

@bp.route('/control/addheatingcircuit', methods=['GET', 'POST']) 
@bp.route('/control/addheatingcircuit/<int:id>', methods=('GET', 
'POST')) 
@login_required
def addheatingcircuit(id=None):
    if id is not None:
        obj = Heatingcircuit.query.get(id) or Heatingcircuit()
        form = AddHeatingcircuitForm(request.form, obj=obj)
        if form.validate_on_submit():
            form.populate_obj(obj)
            db.session.add(obj)
            db.session.commit()
            return redirect(url_for('index.index'))
    else:
        form = AddHeatingcircuitForm()
        if form.validate_on_submit():
            heatingcircuit = Heatingcircuit(name=form.name.data, 
sensor_ID1=str(form.sensor_ID1.data),\ #here i have added 'str'
                           pin_ID1=str(form.pin_ID1.data))
            db.session.add(heatingcircuit)
            db.session.commit()
            flash('Congratulations, you are now a registered a new 
device!')
            return redirect(url_for('index.index'))
    return render_template('control/addheatingcircuit.html', title= 
'add edit heating circuit',
                          form=form)

forms.py

from wtforms_alchemy.fields import QuerySelectField
class AddHeatingcircuitForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
sensor_ID1 = QuerySelectField('sensor_ID1', 
                query_factory=lambda: Sensors.query.all(),
                allow_blank=True, get_label='sensorID')
sensor_ID2 = QuerySelectField('sensor_ID2', 
                query_factory=lambda: Sensors.query.all(),
                allow_blank=True, get_label='sensorID')
.....

models.py

class Heatingcircuit(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    sensor_ID1 = db.Column(db.String(30))
    sensor_ID2 = db.Column(db.String(30))
    sensor_ID3 = db.Column(db.String(30))
    pin_ID1 = db.Column(db.Integer)
    pin_ID2 = db.Column(db.Integer)
    pin_ID3 = db.Column(db.Integer)
    temp = db.Column(db.Float)
    state = db.Column(db.String(9))
    timer = db.relationship('Timers', backref='time')

    def __repr__(self):
        return '{}'.format(self.id)

I have looked at many questions on the forums but this is the closest match Flask WTF 'StringField' object has no attribute 'translate'

So as explained I expect the function on the edit an existing entry part to populate the form with the information already enregistered, and that when I change this and submit the populated form is excepted, instead I get this error message;

AttributeError: 'Heatingcircuit' object has no attribute 'translate'

(full error log possible if needed)

many thanks Paul

EDIT, I am looking at theis tutorial https://www.rithmschool.com/courses/flask-fundamentals/forms-with-wtforms Here it talks about CSRF and a how to disable tokens for iterating over the form, Could my problem be this. This problem affects SelectField as well.

Edit2 I tried the idea mentioned in the link http://wtforms.simplecodes.com/docs/0.6.1/ext.html#module-wtforms.ext.sqlalchemy.fields this code through an error "sqlalchemy.exc.InvalidRequestError: Entity '' has no property 'enabled'" This is my code

def enabled_sensors():
    return Sensors.query.filter_by(enabled=True)

But this failed to EDIT ERROR

Traceback (most recent call last):
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
 File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
  File "/home/pi/heating/homeHeating/control/control.py", line 154, in addheatingcircuit
db.session.commit()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1026, in commit
self.transaction.commit()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 493, in commit
self._prepare_impl()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 472, in _prepare_impl
self.session.flush()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2451, in flush
self._flush(objects)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2589, in _flush
transaction.rollback(_capture_exception=True)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 129, in reraise
raise value
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2549, in _flush
flush_context.execute()
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 236, in save_obj
update,
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 978, in _emit_update_statements
statement, multiparams
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
distilled_params,
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
e, statement, parameters, cursor, context
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1468, in _handle_dbapi_exception
util.reraise(*exc_info)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 129, in reraise
raise value
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1244, in _execute_context
cursor, statement, parameters, context
  File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 552, in do_execute
cursor.execute(statement, parameters)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 168, in execute
query = self.mogrify(query, args)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 147, in mogrify
query = query % self._escape_args(args, conn)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 127, in _escape_args
return {key: conn.literal(val) for (key, val) in args.items()}
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 127, in <dictcomp>
return {key: conn.literal(val) for (key, val) in args.items()}
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/connections.py", line 467, in literal
return self.escape(obj, self.encoders)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/connections.py", line 460, in escape
return converters.escape_item(obj, self.charset, mapping=mapping)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 27, in escape_item
val = encoder(val, mapping)
 File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 118, in escape_unicode
return u"'%s'" % _escape_unicode(value)
  File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 73, in _escape_unicode
    return value.translate(_escape_table)
AttributeError: 'Sensors' object has no attribute 'translate'

I had this same error message for the second half of the "def addpin():" function, I resaerched and found that I needed to return a string so I added str(form.sensor_ID1.data) "str" and this solved the problem there But the first half of the function is the edit part and and I now have the problem there but dont know how to solve it. the error is here I believe;

    if id is not None:
        obj = Heatingcircuit.query.get(id) or Heatingcircuit()
        form = AddHeatingcircuitForm(request.form, obj=obj)
        if form.validate_on_submit():
            form.populate_obj(obj)
            db.session.add(obj)
            db.session.commit()

Thanks for the help Warm regards Paul

1 Answers

0
Nick K9 On

Two problems. First, QuerySelectField's query_factory argument takes a query, not a list of results. So take off the .all():

sensor_ID1 = QuerySelectField('sensor_ID1', 
                query_factory=lambda: Sensors.query,
                allow_blank=True, get_label='sensorID')

Secondly, the data for the given form field is going to give you a Sensors object. So you can't just cast it, you need to ask it for its id. The same goes for the pin_ID1 field. How you do this will depend on how the Sensors class is declared:

heatingcircuit = Heatingcircuit(
    name=form.name.data,
    sensor_ID1=form.sensor_ID1.data.sensorID,
    pin_ID1=form.pin_ID1.data.pinID
)