Tag Archives: django

[Solved] Django Configurate celery error: django.db.utils.DatabaseError

Error on execution of asynchronous task: 

django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias ‘default’ was created in thread id 3047101641304 and this is thread id 3047208084584.

 

Solution:

Original start command (under Windows):
celery -A xxx worker -l info -P eventlet (xxx is the project name)
Modified start command, celery version 4x:
celery -A xxx worker -l info -P solo

[Solved] celery Startup Error: kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions 3.2.0 or later. You have 2.10.6

Error when starting celery:

kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions 3.2.0 or later. You have 2.10.6

The reason is that my redis version is too low and incompatible with kombu. But I won’t touch my redis
uninstall the current celery, download the 4.1.0 version of celery (kombu will be updated during installation), and then start it again. An error is reported:

pip install Celery==4.1.0
error:
KeyError: 'async'

The problem is that version 4.1.0 of celery is incompatible with python3.6.9, so replace it with version 4.1.1 of celery

pip install Celery==4.1.0

Start celery again:

celery -A celery_task.main worker -l info

Done!

 

[Solved] Python Project Error: django.core.exceptions.ImproperlyConfigured: WSGI application ‘WebTool.wsgi.application

Problem Description: run Python project with pychart and report an error: django.core.exceptions.ImproperlyConfigured: WSGI application ‘WebTool.wsgi.application’ could not be loaded; Error importing module.

See the following for complete error reporting:

D:\Python\project\WebTool>python manage.py runserver 0.0.0.0:8080
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 27, 2022 - 09:14:42
Django version 3.2.13, using settings 'WebTool.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application
    return import_string(app_path)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Python\project\WebTool\WebTool\wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__
    self.load_middleware()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 40, in load_middleware
    middleware = import_string(middleware_path)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'corsheaders'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 138, in inner_run
    handler = self.get_handler(*args, **options)
  File "C:\Users\ext.azhang\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super().get_handler(*args, **options)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 65, in get_handler
    return get_internal_wsgi_application()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application
    ) from err
django.core.exceptions.ImproperlyConfigured: WSGI application 'WebTool.wsgi.application' could not be loaded; Error importing module.

Solution: WSGI module needs to be installed

pip install django-cors-headers

Reuse command python manage.py runserver 0.0.0.0:8080 to run the project after installation

After successful operation, see the figure below

[Solved] Forbidden (403) CSRF verification failed. Request aborted.

It is a cross site problem and a Django prevention mechanism. The error reports are as follows:

Generally, this can happen when a genuine cross-site request is forged, or when Django’s CSRF mechanism is not being used correctly. For POST forms, you need to make sure that:
Your browser is accepting cookies.
The view function passes a request to the template’s rendering method.
In the template, each POST form has a {% csrf_token %} template token pointing to an internal URL.

If you are not using the CsrfViewMiddleware, then you must use csrf_protect on any view that uses the csrf_token template tag and on those views that accept POST data.

The form has a valid CSRF token. You may need to reload the page with the form after logging in to another browser tab or clicking the back button after logging in, as the token is rotated after logging in.

You will see the help section of this page because there is DEBUG = True in your Django settings file. changing it to False will only show the initial error message.
You can customize this page using the CSRF_FAILURE_VIEW setting.
As the error message suggests, there are two ways we can do this.
1. go to setting and comment out # ‘django.middleware.csrf.CsrfViewMiddleware’
This is the same as removing the middleware from the cross-site prevention mechanism. Then not this error is reported, but if we really encounter cross-domain problems, we may not know it is reported this error, not very recommended.
2. Add {% csrf_token %} to the form below

[Solved] Windows MYSQL Error: django.db.utils.OperationalError: (2026, ‘SSL connection error: unknown error number‘)

Error Messages:
PS D:\test\orchard_liang>python manage.py sqlmigrate app 0001
Traceback (most recent call last):
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
    self.connect()
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
    self.connection = self.get_new_connection(conn_params)
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection
    connection = Database.connect(**conn_params)
  File "D:\Python37\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "D:\Python37\lib\site-packages\MySQLdb\connections.py", line 179, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2026, 'SSL connection error: unknown error number')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Python37\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Python37\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Python37\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Python37\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 29, in execute
    return super().execute(*args, **options)
  File "D:\Python37\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Python37\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 37, in handle
    loader = MigrationLoader(connection, replace_migrations=False)
  File "D:\Python37\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__
    self.build_graph()
  File "D:\Python37\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "D:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations
    if self.has_table():
  File "D:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table
    with self.connection.cursor() as cursor:
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
    return self._cursor()
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor
    self.ensure_connection()
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
    self.connect()
  File "D:\Python37\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
    self.connect()
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
    self.connection = self.get_new_connection(conn_params)
  File "D:\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
    return func(*args, **kwargs)
  File "D:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection
    connection = Database.connect(**conn_params)
  File "D:\Python37\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "D:\Python37\lib\site-packages\MySQLdb\connections.py", line 179, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number')

Reason: SSL of the higher versions of MySQL is turned on by default
solution: turn off SSL

Step 1: check the SSL startup first

Login mysql and then enter the commands below:
mysql> SHOW VARIABLES LIKE '%ssl%';

Step 2: Modify the configuration file my.ini

# PATH: C:\ProgramData\MySQL\MySQL Server 8.0
[mysqld]
skip_ssl  # ssl

Step 3: restart MySQL service

ctrl+shift+esc key to call up task manager -> services -> find mysql service -> right click and rerun

Step 4: re execute the command:

mysql> SHOW VARIABLES LIKE '%ssl%';


Django CSV file Error: UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xb5 in position 0: invalid start

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xb5 in position 0: invalid start

This csv file I opened in jupyter using pd.read_csv open no problem

But after I cleaned the data and saved it as a new csv, I couldn’t open it and got an error

Solution: in the views.py direct cleaning work, the data will be stored in order into a list, using a loop to iterate through the database, the following is the code (less efficient after all is iterative. Welcome to share a better way)

df = pd.read_csv(r"xxxxx\xxx.csv", encoding='utf-8')
... # datas clean up
ls = []
for index, row in df.iterrows():
     res = []
     for i in df:
         res.append(row[i])
            ls.append(res)
for i in range(len(ls)):
    try:
        XXX.objects.create(title=ls[i][0], rating=ls[i][1])
    except Exception as e:
        print(e)
return HttpResponse('Datas save successfully')

How to Solve Vue & Django Cross-domain Issue

1. Install the package to solve cross-domain related problems at the terminal

python -m pip install django-cors-headers

2. Add the following configuration to the setting.py file clock in the django project

‘corsheaders’,

comment csrf out and add  ‘corsheaders.middleware.CorsMiddleware’,

finally add these two lines of configuration

[Solved] Django project locally Open Error: importerror: couldn’t import Django

There is a mature Django project. After it is opened locally, an error is reported: importerror: couldn’t import Django Are you sure it’s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
solution step 1: because this Django project uses python2.7. My local configuration environment variable is 3.7.7. After importing the Django project locally, the python compiler has been modified to 2.7

but an error is still reported after execution
solution step 2: open the teminal terminal of pycharm

execute the command: source venv/bin/activate
start the Django project: Python manage Py runserver

the Django project was started successfully and the problem was solved perfectly.

[Solved] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.Did you install mysqlclie

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 122, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/options.py", line 207, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 15, in __getattr__
    return getattr(self._connections[self._alias], item)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 62, in __getitem__
    conn = self.create_connection(alias)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 204, in create_connection
    backend = load_backend(db['ENGINE'])
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 20, in <module>
    ) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

One of the reasons for this error when starting the Django project is:

Because pymysql is not installed or not configured,

Pymysql is not installed. It needs to be built into the environment and executed

import pymysql
pymysql.install_as_MySQLdb()

Done!