Category Archives: Python

[Solved] Django database Modify Warning: Did you rename house.houseid to house.id (a BigAutoField)? [y/N] n

1. Problem description

In Django, models Add an order table in the PY file. When migrating through the “py manage.py makemigrations” command, I find that a small black box appears, asking me to rename the ID of the existing table in the database, prompting that adding a non empty “Id” to an existing house table is not allowed; Specific tips are as follows:

2. Problem solving

The following solutions have been tried:

1. Comment out models The code of the new order table in py re executes “py manage.py makemigrations”, and it is found that the above error is still prompted.

2. Someone in stackoverflow has encountered a similar situation (the specific link is here), and the reply solution is as follows:

This might sound dumb but did you perhaps run a find and replace in your project where you replaced id with pid? Django automatically generates primary key fields with the name id not pid. This or perhaps previously you ran a modified version of Django which generated fields named pid instead of id is what I can think happened. As below comment states just edit your migration files and correct them.

The main idea is that this problem is quite outrageous. It is possible that the user-defined primary key in models is ID, but the PID is used in the code;

After checking the code, it is found that one interface with parameters uses “houseid” instead of models After replacing “houseid” with “Id” in the customized primary key “Id” in py, run “py manage.py makemigrations” and find no error.

 1 views.py
 2 
 3 def addToHouseOrder(request, houseid):
 4     """
 5     Users add houses to the order list
 6     :param request:
 7     :param id: houseid
 8     :return:
 9     """
10     if request.method == "GET":
11         currentUser = request.session['username']
12         print(currentUser, houseid)
13         houseResult = House.objects.filter(id=houseid)
14         return HttpResponse(houseid)
15     elif request.method == "POST":
16         pass

python csv error: line contains null byte [How to Solve]

Problems inherent in Python’s CSV package

Practice has proved that when using CSV to read a file, once the file contains a string of ‘\0’ or ‘\X00’, an error will be reported and ‘line contains null byte’ will be displayed.

Part of the reason is that there is such a string in the file itself. Another possible reason is that the CSV file is converted from excel file. The simple way to deal with it is to save it as CSV again.

If you do not want to modify the file, you need to extract these possible null bytes. The following codes:

        with open(path, 'r', encoding="UTF8") as f:
            reader = csv.reader((line.replace('\0', '') for line in f), delimiter=",")
            for row in reader:
                print(row)

[Solved] Python runs import CV2 error: Legal instruction (core dumped)

Import CV2 error legal instruction (core dumped) solution

After opencv is installed on the nanopc-t4 development board, an error of legal instruction (core dumped) will be reported when importing CV2, which is caused by problems such as the kernel. Through searching for data in many ways, a preliminary solution has been found.

Run from the command line

Solution to error reporting during command line operation:

Run openblas_CORETYPE=ARMV8 python3

Python file running

.py file operation error report solution:

The terminal runs sudo GEDIT ~ /.Bashrc

Add the environment variable export openblas at the end_Coretype = armv8 , save and close

Terminal running source ~ /.Bashrc

[Solved] Djiango Create Migrations Error: query = query.decode(errors=’replace’) AttributeError: ‘str’ object has no attribute ‘decode’

When creating migrations at the terminal command line, enter (python manage.py makemigrations) or (python manage.py migrate) with the error message:
Traceback (most recent call last):

File “manage.py”, line 21, in
main()
File “manage.py”, line 17, in main
execute_from_command_line(sys.argv)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management_init_.py”, line 381, in execute_from_command_line
utility.execute()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management_init_.py”, line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\base.py”, line 323, in run_from_argv
self.execute(*args, **cmd_options)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\base.py”, line 364, in execute
output = self.handle(*args, **options)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\base.py”, line 83, in wrapped
res = handle_func(*args, **kwargs)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\commands\makemigrations.py”, line 101, in handle
loader.check_consistent_history(connection)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\migrations\loader.py”, line 283, in check_consistent_history
applied = recorder.applied_migrations()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\migrations\recorder.py”, line 73, in applied_migrations
if self.has_table():
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\migrations\recorder.py”, line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\base\base.py”, line 256, in cursor
return self._cursor()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\base\base.py”, line 233, in _cursor
self.ensure_connection()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\base\base.py”, line 217, in ensure_connection
self.connect()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\base\base.py”, line 197, in connect
self.init_connection_state()
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\mysql\base.py”, line 232, in init_connection_state
if self.features.is_sql_auto_is_null_enabled:
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\functional.py”, line 80, in get
res = instance.dict[self.name] = self.func(instance)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\mysql\features.py”, line 82, in is_sql_auto_is_null_enabled
cursor.execute(‘SELECT @@SQL_AUTO_IS_NULL’)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\utils.py”, line 103, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File “C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\mysql\operations.py”, line 146, in last_executed_query
query = query.decode(errors=‘replace’)
AttributeError: ‘str’ object has no attribute ‘decode’

**Solution**

C:\Program Files (x86)\Python37-32\Lib\site-packages\django\db\backends\mysql\operations.py
Change decode to encode to solve
Find the corresponding file and open it, modify the content:

Then go back to cmd and re-enter the command

[Solved] TypeError: ‘Collection’ object is not callable. If you meant to call the ‘authenticate’ method on a ‘Database’ object it is failing because no such method exists.

After installing the environment on the new computer these two days, it was found that the previous code could not authenticate the mongodb database user, and an error was reported, as shown in the title. After checking, it was found that there was a problem with the pymongo version

In pymongo version 3.9, the user authentication code is as follows:

self.client = pymongo.MongoClient(host="127.0.0.1", port=27017)
self.client["admin"].authenticate("admin", "12345678")

In pymongo 3.9 and before, it can run normally and perform user authentication. When I upgrade to 4.0, the error is reported as follows

Traceback (most recent call last):
  File "/Users/zzq/PycharmProjects/downloads_data/mongo_utils.py", line 34, in <module>
    mongo = Mongo()
  File "/Users/zzq/PycharmProjects/downloads_data/mongo_utils.py", line 13, in __init__
    print(self.client["admin"].authenticate("admin", "12345678"))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pymongo/collection.py", line 2579, in __call__
    raise TypeError("'Collection' object is not callable. If you "
TypeError: 'Collection' object is not callable. If you meant to call the 'authenticate' method on a 'Database' object it is failing because no such method exists.

After viewing the official documents, it is found that the explanation is as follows:

4.0 document address: https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html#database-authenticate-and-database-logout-are-removed

It’s very clear here. In the new version, the previous authentication method is removed and the user name and password parameters are entered during instantiation, so my code is updated as follows:

self.client = pymongo.MongoClient(host="127.0.0.1", port=27017,username="admin",password="12345678")  # 地址  端口  用户名  密码

If you don’t know what version your pymongo is, you can use PIP3 list – V or pip list – V to view it and choose according to your situation

In addition to rewriting the code, you can also downgrade pymongo to 3.9   You can also make the code run normally. First, use PIP3 uninstall pymongo, enter y to delete it, and then specify the pymongo version as 3.9 when installing again: PIP3 install pymongo = = 3.9

[Solved] Selenium Error: ElementClickInterceptedException

The error message is as follows:

The general meaning is that the current element is not clickable, but it does exist on the page, and it may be overwritten by loading
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <button data-v-3916f4c2="" type="button" class="el-button el-button--primary" style="width: 100% ; height: 50px; border-radius: 10px; margin-top: 20px;">...</button> is not clickable at point (688, 398). Other element would receive the click: <div data-v- 3916f4c2="" class="login-top">...</div>

Solution 1: Force to wait for a few more seconds
# Can be forced to wait
import time
time.sleep()
Solution 2: Call js directly through selenium
js = driver.find_element(By.CSS_SELECTOR, ‘xxx’)
driver.execute_script(“arguments[0].click();”, js)

Display waiting:
The visibility_of_element_located used here is different from presence_of_element_located
visibility_of_element_located: After the element is found, the width and height of the element must be greater than 0 to execute;
presence_of_element_located: Execute directly after the element is found, maybe the element is covered by a mask, or the loading mask will cause you to be unable to click
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
try:
element = WebDriverWait(driver, 5).until(ec.visibility_of_element_located(loc))
except TimeoutException:
element.click()

[Solved] rosrun import rospy Error: ImportError: No module named yaml

rosrun Error:

Traceback (most recent call last):
File "/home/ving/catkin_ws/src/hello_tutorial/src/hello.py", line 3, in <module>
import rospy
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/__init__.py", line 47, in <module>
from std_msgs.msg import Header
File "/opt/ros/noetic/lib/python3/dist-packages/std_msgs/msg/__init__.py", line 1, in <module>
from ._Bool import *
File "/opt/ros/noetic/lib/python3/dist-packages/std_msgs/msg/_Bool.py", line 6, in <module>
import genpy
File "/opt/ros/noetic/lib/python3/dist-packages/genpy/__init__.py", line 34, in <module>
from . message import Message, SerializationError, DeserializationError, MessageException, struct_I
File "/opt/ros/noetic/lib/python3/dist-packages/genpy/message.py", line 48, in <module>
import yaml
ImportError: No module named yaml

 

Reason: there are two versions of python locally
Check the current version: /usr/bin/python –version
Solution:

sudo ln -sf /usr/bin/python3 /usr/local/bin/python