I have a django view that causes FOREIGN KEY constraint failed. This is coming from a related question
def return_book(request,pk):
books = Books.objects.filter(school = request.user.school).get(id = pk)
book = Issue.objects.get(book_id_id=pk,book_id__school_id = request.user.school.id)
user = CustomUser.objects.get(id=request.user.id)
Return.objects.create(borrowed_item_id=book.id,returner=user)
Books.Addbook(books)
Issue.objects.get(book_id_id=pk).delete()
return redirect("view_books")
The erro is returned at Issue.objects.get(book_id_id=pk).delete()
I don't know the exact cause of this error. Could somebody explain to me what's going on hat causes the error>
The Traceback is below.
Traceback (most recent call last):
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 209, in return_book
Issue.objects.get(book_id_id=pk).delete()#Borrower_id is also required in the filter
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 947, in delete
return collector.delete()
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\deletion.py", line 396, in delete
count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 43, in delete_batch
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 23, in do_query
cursor = self.get_compiler(using).execute_sql(CURSOR)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
class Issue(models.Model):
borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
issue_date = models.DateField(default=datetime.date.today)
issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
class Return(models.Model):
return_date = models.DateField(default=datetime.date.today)
borrowed_item = models.ForeignKey(Issue,on_delete=models.DO_NOTHING)
returner = models.ForeignKey(CustomUser,on_delete=models.DO_NOTHING)
Do DO_NOTHING is typically not a good option since (most) databases will check referential integrity. This means that they guarantee that if a ForeignKey refers (in this case to an Issue), then that means that the table that stores the issues should have a record with the primary key the Return item refers to.
Often DO_NOTHING is used in combination with a certain trigger in the database system (that Django is not aware of).
Typically the most popular choices foron_delete are:
models.CASCADE: in that case it will remove all Returns related to the removed item;
models.PROTECT: in that case it will raise an error to prevent removing the Issue; and
models.SET_NULL: this is done on a NULLable field (so with null=Ture), in which case the impacted Return(s) will set the field to NULL/None.
Another option might be to "soft delete" records, for example with the django-soft-delete package [pypi]. In that case a boolean is added to the Issue that specifies if the item is removed. The package will also transparently filter the objects, such that you only retrieve records that are "alive".
This edge case is not directly relevant for the OP, but may help others that wind up here based on the title:
An IntegrityError: FOREIGN KEY constraint failed will also be raised when trying to delete some object x, if there is a table in your database that Django is unaware of, and this table has a reference to object x.
This can happen, for example, if you remove a model from your code without properly migrating the changes.
As a result, the table remains in the database, but Django does not know anything about it, so, when object x is deleted, Django does not know it should also delete the corresponding row from this "orphaned" table.
Related
I'd like to request aggregated trade data beginning at a certain timestamp until now
client.get_aggregate_trades(symbol = 'EURBUSD', startTime = 165605516493)
but i only get an Error:
File "c:\Users\Pascal\Python Skripts\Binance\test.py", line 39, in
aggregate = client.get_aggregate_trades(symbol = ticker, startTime = 165605516493)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 743, in get_aggregate_trades
return self._get('aggTrades', data=params, version=self.PRIVATE_API_VERSION)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 371, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 334, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 315, in _request
return self._handle_response(self.response)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 324, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1128): Combination of optional parameters invalid.
Even if i input all possible parameters (start and end time less than 1 hour), it still throws the same Error. What am i missing here?
Thank you a lot for helping.
I had the same problem.
I fixed it by adding an "endTime" parameter to the "get_aggregate_trades".
client.get_aggregate_trades(symbol='BTCUSDT', startTime='1534130155000', endTime='1534130169000')
I am using django-pgcrypto package to work with encripted data. In documentation says that is possible to filter on encrypted fields as you would normal fields via exact, gt, gte, lt, and lte lookups this package for encryption.
Model:
class Profiles(BaseModel):
first_name = EncryptedCharField(max_length=255, null=True)
last_name = EncryptedCharField(max_length=255, null=True)
postal_code = models.CharField(max_length=32, null=True)
skype = EncryptedCharField(max_length=255, null=True)
email = EncryptedCharField(max_length=255, null=True)
...
Example of query:
email = Profiles.objects.filter(email__exact='example#email.com')
Error:
Traceback (most recent call last):
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedFunction: function dearmor(text) does not exist
LINE 1: ...irmed" FROM "profiles" WHERE convert_from(decrypt(dearmor("p...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/Projects/rab/rentautobus-site/uService2/traveler/views.py", line 206, in conversations
print(email)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
self._fetch_all()
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1097, in execute_sql
cursor.execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: function dearmor(text) does not exist
LINE 1: ...irmed" FROM "profiles" WHERE convert_from(decrypt(dearmor("p...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
If you read the documentation, it says here:
You must also make sure the pgcrypto extension is installed in your database. Django makes this easy with a CryptoExtension migration.
Your error log shows that you have yet to do this, and Django's documentation covers how to create a PostgreSQL extension in your database using a migration file CryptoExtension migration here.
The operation on your migration file looks like:
from django.contrib.postgres.operations import CryptoExtension
class Migration(migrations.Migration):
...
operations = [
CryptoExtension(),
...
]
Note that you have to set up the crypto extension in PostgreSQL before the first CreateModel or AddField operation that involves EncryptedCharField; So run this migration with the CryptoExtension operation before your you introduce EncryptedCharField.
If you rather not do it with a migration file, you can install the pgcrypto extension on your database directly. Assuming you're on PostgreSQL 9.1+, the [answer] here shows you how to install that extension on linux systems that use apt (or apt-get). Copying from Dustin's answer (linked to above),
sudo apt-get install postgresql-contrib
Once installation is completed, run this in your psql shell:
postgres#ztrustee:~$ psql test
psql (9.1.3)
Type "help" for help.
test=# CREATE EXTENSION pgcrypto;
CREATE EXTENSION
Once that is done, run your Django migrations again.
I’m creating a django based web app and I have used Auth > User model (without any customization except password hiding) and for user detail I have created another model ChangeShift. and model based form.
Case 1: When I am using alluser = ShiftChange.objects.all() I'm able to see all the data available in ShiftChange model.
Case 2: Now I want that when user is logging, he should be able to see data related to his name and I'm using this:
def retrieve_view(request):
# alluser = ShiftChange.objects.all()
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
return render(request, 'apple/shift2.html', {'alluser': alluser})
For this code I am getting error:
cannot unpack non-iterable bool object
Error Traceback:
[21/Sep/2020 11:13:18] "GET /static/css/auth.css HTTP/1.1" 404 1662
Internal Server Error: /alldata/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/shaileshyadaav/djangoshaileshdurga/mapsIT/apple/views.py", line 53, in retrieve_view
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable bool object
The line:
alluser = ShiftChange.objects.filter(
ShiftChange.ldap_id == request.user.username)
is the error. The part ShiftChange.ldap_id == request.user.username is an expression that evaluates to True or False, and then your code becomes equivalent to
alluser = ShiftChange.objects.filter(True)
or
alluser = ShiftChange.objects.filter(False)
and that is probably not what you want.
Try using a single = sign and use a valid left side kwarg (because ShiftChange.ldap_id with the dot in the middle is not valid here).
So your code may end up similar to this:
alluser = ShiftChange.objects.filter(ldap_id=request.user.username)
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
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
)
Although a couple of similar question were posted, none of those questions are the same as my case.
I had a model that looked like this:
class Person(models.Model):
"""Definition of persons that will fulfill a role in a committee
or will be in a way associated with a committee as an administrator
"""
ClientId = models.ForeignKey('clients.Client', on_delete=models.CASCADE,
to_field='id')
PersNumber = models.PositiveIntegerField(null=False)
PersSurName = models.CharField(max_length=40, null=False)
PersNames = models.CharField(max_length=40, null=False)
I set the uniqueness of the record on ClientId and PersNumber.
I have created 3 records in the database.
Along the way I became convinced that I might as well use the auto generated id of the record as the person number (I am learning Django).
I removed the PersNumber from my model and ran makemigrations.
All is well until I ran migrate...
I get the following error:
django.core.exceptions.FieldDoesNotExist: Person has no field named 'PersNumber'
Any idee on how to get past this error
The full trace looks like this:
Operations to perform:
Apply all migrations: admin, auth, clients, contenttypes, komadm_conf, sessions
Running migrations:
Applying komadm_conf.0017_auto_20180830_1806...Traceback (most recent call last):
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\models\options.py", line 564, in get_field
return self.fields_map[field_name]
KeyError: 'PersNumber'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 15, in
execute_from_command_line(sys.argv)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
fake_initial=fake_initial,
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\migrations\operations\fields.py", line 150, in database_forwards
schema_editor.remove_field(from_model, from_model._meta.get_field(self.name))
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 318, in remove_field
self._remake_table(model, delete_field=field)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 257, in _remake_table
self.create_model(temp_model)
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\backends\base\schema.py", line 300, in create_model
columns = [model._meta.get_field(field).column for field in fields]
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\backends\base\schema.py", line 300, in
columns = [model._meta.get_field(field).column for field in fields]
File "C:\ApplicationDef\za\co\drie_p\Komadmin.db\KomAdmin\KomadmTest\komadm_app\komadm_env\lib\site-packages\django\db\models\options.py", line 566, in get_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Person has no field named 'PersNumber'
Giving the fact that nobody else answered i will(but i am learning too)..
did you check if this field still exist ? (in the shell for instance).
i'll recommand to manually delete the migration file associated and try again (makemigrations + migrate).
The migration file i am talking about can be found MyProject/Myapp/migrations/00xx_something.py
If it still does not work you can delete the table directly in your database, and the migration file associated.