Tag Archives: python

[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.

VScode debug error: configured debug type ‘Python’ is not supported

When using vscode to debug, an error is reported in the pop-up window:

Configured debug type 'python' is not supported

Refer to the reference website: https://github.com/microsoft/vscode/issues/136712

The measured solution is metaphysical, as follows:

Delete Jupiter and python in vscope extensions, and then reinstall them; Close all vscodes; (this step is very important.) Open vscode again and you can debug normally.

Pycharm error: original error was: DLL load failed while importing _multiarray _Umath: the specified module could not be found

Anaconda is installed under the window system and the virtual environment is configured
everything runs normally using the command line, but an error is reported when running on pychram:
original error was: DLL load failed while importing _multiarray _umath

Tried:
1. Uninstall numpy and reinstall numpy
2. Add the python path again many times in the python settings

Final solution:
add system variables

after installing anaconda, only the first two are added, but not enough!!! \Bin and \library\bin should also be added!!!

Since it runs normally on the command line, the version problem between packages can be ignored. The problem must be the configuration of pycharm or system variables

Reference link: https://github.com/conda/conda/issues/7833

[Solved] UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xbf in position 7: invalid start byte

The code is as follows:

f = csv.reader(open(csvroot, 'r',encoding='utf-8'))
for i in f:
    print(i)

Solution: view the file encoding format

import chardet

f = open(full_csvroot, 'rb')
data = f.read()
print(chardet.detect(data))

# Outcome:
# {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}

Amend to read:

f = csv.reader(open(csvroot, 'r',encoding='GB2312'))
for i in f:
    print(i)

Perfect operation

[Solved] python Error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.

Python Error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Error Codes:

if (code in list(changed_code['Old material code'])):
            temp_index = changed_code.loc[changed_code['Old material code'] == code].index

The type of code here is float.

Cause analysis:

In this judgment method, the judged value cannot be of float type.

Solution:

Just convert float format to int format

if (int(code) in list(changed_code['Old material code'])):
            temp_index = changed_code.loc[changed_code['Old material code'] == code].index

Solve the problem, brothers, get better!!

[Solved] python-sutime Error: the JSON object must be str, bytes or bytearray, not ‘java.lang.String‘

Problems arising

The JSON object must be STR, bytes or byte array, not ‘Java.lang.String’

Solution:

The last in sutime.py is this:

	return json.loads(self._sutime.annotate(input_str, reference_date))
return json.loads(self._sutime.annotate(input_str))

Replace it with:

	return json.loads(str(self._sutime.annotate(input_str, reference_date)))
return json.loads(str(self._sutime.annotate(input_str)))

 

Test sutime package (this part is also referred to the above website)

import json
import os
from sutime import SUTime

if __name__ == '__main__':
    test_case = "I need a desk for tomorrow from 2pm to 3pm"
    # D:/python_projects/SPARQA/common_resources/resources_sutime/python-sutime-master/jars
    jar_files = os.path.join(os.path.dirname('D:/python_projects/SPARQA/common_resources/resources_sutime/python-sutime-master/jars'),'jars')
    sutime = SUTime(jars=jar_files, include_range=True)
    print(json.dumps(sutime.parse(test_case), sort_keys=True, indent=4))

The operation result is:

[
    {
        "end": 26,
        "start": 18,
        "text": "tomorrow",
        "type": "DATE",
        "value": "2021-12-31"
    },
    {
        "end": 35,
        "start": 32,
        "text": "2pm",
        "type": "TIME",
        "value": "2021-12-30T14:00"
    },
    {
        "end": 42,
        "start": 39,
        "text": "3pm",
        "type": "TIME",
        "value": "2021-12-30T15:00"
    }
]

[Solved] Error: Please select a valid Python interpreter

Before that

First download Python and configure environment variables

Win11python download and environment variable configuration

Text

Reference link:
Python learning notes – error: Please select a valid Python interpreter

Question

The following error occurs when running: Please select a valid Python interpreter
the English meaning of this sentence: “please select a valid Python interpreter”

In fact, it’s because you just downloaded pychar, and you haven’t done its basic configuration yet. The error is normal ~

Solution:

First, Download python (again)

Open the DOS command line window,

ah, with ~

Then, the parser selects the problem, opens settings (Ctrl + Alt + s) or file & gt; settings, and opens the configuration box, as shown in the following figure:

Just follow the steps:

The results are shown in the figure below:

Then you can!

[Solved] AttributeError: ‘DataFrame‘ object has no attribute ‘tolist‘

 

solve the problem

return object.__getattribute__(self, name)
AttributeError: ‘DataFrame’ object has no attribute ‘tolist’

Solution ideas

Property error: ‘dataframe’ object does not have property ‘tolist’

Solution:

Remember that DataFrame does not have a tolist() method, but series.Series has a tolist() method, so it needs to be modified

take

import pandas as pd

#Read xls file
file_path='data/test1226.xls'
data_frame_xls=pd.read_excel(file_path)
data_df01 = data_frame_xls[['age']]
print(type(data_df01))
print(res)

Change to

import pandas as pd

#Read xls file
file_path='data/test1226.xls'
data_frame_xls=pd.read_excel(file_path)
data_df01 = data_frame_xls[['age']]
print(type(data_df01))

data_df01 = data_frame_xls['age']
print(type(data_df01 ))
res = data_df01 .tolist()
print(res)

Ha ha, it’s done!

[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!

NameError: name ‘xrange‘ is not defined [How to Solve]

The reason is that my Python version is Python 3.8, while the xrange() function is in Python 2.0 For a function in X, in Python 3, the implementation of range () is the same as that of xrange (), so there is no special xrange (). Therefore, when this problem is encountered, there are two methods to solve it.

Solution:

1: if you want to run the program in Python 3, change all xrange() functions to range().

2: put the program with this problem in Python 2.X version of the environment can be run