Tag Archives: django

fatal error: Python.h: No such file or directory

Error:
system centos7.4 64-bit
python 2.7.5
plugins/python/uwsgi_python.h:2:20: fatal error: Python.h: No such file or directory
#include < Python.h>
Command “/usr/ bin/python2-u-c” import setuptools, tokenize;
Command “/usr/ bin/python2-u-c” import setuptools, tokenize; The file = ‘/ TMP/PIP – build – r2TLym uwsgi/setup. Py “; F = getattr (tokenize, open, open) (file); Code = f.r ead (). The replace (‘ \ r \ n ‘, ‘\ n’); f.close(); exec(compile(code, file, ‘exec’)) “install –record/TMP/pip-jwt5ox-record /install-record. TXT –single-version –compile” failed with error code 1 in/TMP/pip-build-r2tlym /uwsgi/

Check the solution:
yum install python-devel.x86_64
Then run the installation and fix the problem.

django.core.exceptions . improverconfigured: mysqlclient 1.4.0 or new is required; you have

Django. Core. Exceptions. ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; You have solutions for 0.10.1
An error occurred today when replacing mysql database while learning django:
is written in _init_. Py

import pymysql
pymysql.install_as_MySQLdb()

Error: the django. Core. Exceptions. ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; You have 0.10.1.
This is actually a mismatch between django and Pymysql. Python3 is not supported by mysqldb.
1. Tried to comment the python/Lib/site – packages/django/db/backends/mysql/base. Py files
' ' 'if the version & lt; (1, 4, 0): Raise ImproperlyConfigured(' mysqlClient 1.4.0 or Newer is required; You have %s.' % Database.) '
2. Updated version of Django, also useless
Final solution:
init.py is changed to

import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()

Specify the Pymysql version directly
Xiaobai learns Python, if there is a mistake, please give me more advice

Django reads the txt file in view

Problem description:
In view, you want to load a TXT of block-words to block out dirty words.
but cannot find the file
Solutions:
Use the full path, put TXT under the same path as view.py, and add the first two lines

module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'block-words.txt')  # full path to text.
block_words = pd.read_csv(file_path,header=None)

Subsequent operation:
Use find to match, replacing all matched words with asterisks

for word inblock_words[0]:
    if info.find(word) != -1:
        info = info.replace(word, '*' * len(word))

Four ways to get Django parameters in request

1. Query string data (String)
Like:?key1=value1& Key2 = value2
use

requisition.get ("key", "value") GET
2. request-getlist ("key", []) GET the last value

Ii. Request Body Data (BODY) :
For example: form data, JSON,…
2.1 form data :(only post requests are supported)

request.POST.get("name", "")

2.1 json data :(post and put requests are supported)

Loads (json_str) json_str = request. Body # attribute to get the original request data
json_dict = json.json (json_str)# convert the original data into dictionary format
json_dict. Get ("key", "default value ") # get the data

3. Specific part of data in the URL path

Regular, or routing converter

4. Request Header Data (HEADER) :

request.MEAT.get("key")

Django debug = false internal server error 500

Add the following in Setting.py

# AMDIN CONFIGURATION
#-------------------------------------------------------------------------------
ADMINS = [('hiveme', '[email protected]')]

# EMAIL CONFIGURATION
#-------------------------------------------------------------------------------
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

When set from this, if the server generates 500 errors it prints the error message to the log/screen. You can also set up other EMAIL_BACKEND so that it will email errors to your email.

django.core.exceptions . improveconfigured: error loading MySQL DB module. Django configuring MySQL database

A, errors,

Traceback (most recent call last):
  File "/home/ubuntu/anaconda2/envs/python3/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 "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
    app_config.import_models()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/home/ubuntu/anaconda2/envs/python3/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/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/utils.py", line 202, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/ubuntu/anaconda2/envs/python3/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?

Ii. Problem Solving
1. Source of problem
After installation of Django, the default database driver is sqlite, but I do not have sqlite database, so change to
mysql, then go to the directory first/first/settings.py, and find:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Modified to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'first',
        'USER': 'python',
        'PASSWORD': '123456',
        'HOST': '192.168.99.124',
        # 'PORT': '',
    }
}

Run the command python manage. Py runserver then executes to start the service at the following Error:
django. Core. Exceptions. ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
2. Solve
Obviously, there is no mysql driver installed, just install it, so I quickly typed the command line:

pip install mysql-python

ImportError: No module named 'ConfigParser'
Python3.x is changed to lowercase relative to PYTHON 2.x, indicating that THE MYSQL python in PIP does not support Python3.x. Maybe the update in PIP is relatively slow, so we will download their source code installation. However, the latest update date of the source code is 2012, and there is still no support for Python3.x!
How does this work?Change the support python3 driver try, heart energizes, grass mud horse, of course, as a result on making a search, found a PyMySQL (https://github.com/PyMySQL/PyMySQL), which, of course, also have it in the PIP, then I quickly on the command line with:

pip install PyMySQL

Django does not recognize this alien monk, how to do, or to do, find mysite/mysite/init.py, enter the following content and save:

import pymysql
pymysql.install_as_MySQLdb()

Then When I ran Python Manager.py Runserver, another prompt popped up:
You have unapplied migrations; Run 'Python manage. Py Migrate' to apply them.
Of course, this prompt does not affect the operation of the native server. At this time, when we visit http://127.0.0.1:8000, we will see the successful prompt:

It worked!

Congratulations on your first Django-powered page.

Of course, you haven't actually done any work yet. Next, start your first app by running python manage.py startapp [app_label].

You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

Of course, I didn't like the warning, and he told me what to do to get rid of him, of course! I quickly copy the contents to the command line:

python manage.py makemigrations
python manage.py migrate

Then restart the service, it's normal!


The environment

    Python version: 3.6.0Django version: 2.5

A server error occurred. Please contact the administrator.

In terms of Django site management, login to site Admin, if there is a problem with a title, it could be for the following reasons:
1, localization, letter case didn’t pay attention to, the right is LANGUAGE_CODE = 'useful - Hans' and TIME_ZONE =' Asia/Shanghai ', then analysis is setting up the contents of the file has been changed after cannot be interpreter identification, so later met the same problem can according to this train of thought analysis (then if new create a project to try again, or if the original error, Maybe the previous project wasn't closed). 2. Without the model migration, the data table of the project will not be generated, and the login site is the operation of the data table, without the migration even without the table, how can you log into the site?

Error loading pscopg2 module: no module named pscopg2

When using Django to connect to a postgresql database, use python manager.py migrate to create a database.
django. Core. Exceptions. ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' solution:
apt install psycopg2 if it fails, don't care if apt install libpq-dev or apt install postgresql-server-dev-x.y must be installed successfully, one of them PIP install psycopg2 must be installed successfully. Finally, remember to set an access password for the database set in your setting. Py , otherwise an error will be reported. You can set the access password by referring to the relevant commands here.

A server error occurred. Please contact the administrator.

preface
Regarding the site management of Django, the login site admin encountered A server error “A Server error occurred. Please contact the Administrator.”
why
Localization, letter case didn’t pay attention to, the right is LANGUAGE_CODE = 'useful - Hans and TIME_ZONE =' Asia/Shanghai , then analysis is setting up the contents of the file is changed after cannot be interpreter identification, so later met the same problem can according to this train of thought analysis (then if new create a project to try again, or if the original error, before the project could be open). Without the model migration, the project's data tables will not be generated, and the login site is a data table operation. Without the migration, how can you log into the site if there are no tables?

Python: What’s Virtualenv

The Python virtualenv
Install VirtualEnv2.1 Install Virtualenv2.2 Create virtual Environment 2.3 Activate/exit virtual Environment
3. TIps

1. What is VirtualEnv
Virtualenv is short for Virtual Environment, meaning a virtual environment.
so what’s good about python using it?Some!
suppose I did A project A before, using Django2.2. Now that there is a new version of Django3.1, I want to use the latest version of Django. The problem is that I installed the new version of Django, and project A using the old version may not run smoothly.
this is where virtualenv comes in. It can create multiple virtual environments simultaneously, allowing multiple versions of Django to exist on a single computer.
2. Install VirtualEnv
2.1 install virtualenv

pip install virtualenv

2.2 Create a virtual environment
Create a virtual environment.
command format:
virtualenv+ environment name


virtualenv test_env1
virtualenv test_env2

2.3 Activate/exit the virtual environment
Enter the virtual environment, and then you can install the package in the virtual environment.

Win:
	Run\Scripts\activate access a virtual environment
	Run\Scripts\deactivate exit a virtual environment

3. TIps
There is no package installed in the virtual environment and a re-pip is required. The Python interpreter is in the /Scripts/ Python.exe directory.

Solutions to Django is not importable in this environment

Django is not importable in this environment.
(1) the first thing to illustrate the point, now on the network all kinds of copy, about today I encountered this problem, didn’t find a good way to online, and open a, then open a, completely identical copy, was no, really is too sad, to solve the problem it took me 4 to 5 hours (I am a rookie!
If this article does not obtain my consent, do not reprint and plagiarism!
(2) PyCharm downloaded from the Internet or copied from other computers cannot be opened directly, and some Settings need to be made, which is very annoying! Of course, the main problem is to set up the interpreter, but there are other problems, such as Django is not importable in this environment. My software version is python3.4.3 and django 2.0.7
(3) Solutions to this problem:
The file – & gt; Open, find your project file (project name), as follows, my project file is under the Learn folder, which has 4 projects

Then look at the following:
Select open in the new window to open a new window. Select another window to close the one you are currently open.

My entire project list is as follows:

It doesn’t matter that my project name is not the same as zaxt_tMP12 under the project.
And then: file – & gt; Settings – & gt; Project Interpreter

Then, look at the picture:

Hide interpreters that connect to other projects:

The effect is as follows, then green + :

If it’s OK, the result is like this (don’t follow it here, I’m just showing you!! :

Django is not importable in this environment if you don’t grab Inherit global site-packages, you will get an error when you run.



Very distressed! ?You’ve been messing with me for a long time. In fact, here’s what you should do:

Then, apply – & gt; ok

Django is out!!
(4) Finally, add an interpreter:

Select the interpreter we set up in the previous step! And run manager.py Runserver. Click Run again and you’re ready to run!

It took quite a while to write the document, redid it and liked it if it helped.
If this article does not obtain my consent, do not reprint and plagiarism!

ubuntu install mysqlclient error ERROR: Failed building wheel for mysqlclient solution

Under Windows error
This site has been written by many predecessors, go to this site to download the corresponding file installation is good I will not teach fish to swim.
An error under ubuntu

(cai_django) ubuntu@VM-0-2-ubuntu:~$ pip3 install mysqlclient
Looking in indexes: http://mirrors.tencentyun.com/pypi/simple
Collecting mysqlclient
  Downloading http://mirrors.tencentyun.com/pypi/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.ta
     |████████████████████████████████| 92kB 711kB/s 
Building wheels for collected packages: mysqlclient
  Building wheel for mysqlclient (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/ubuntu/.virtualenvs/cai_django/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jqj_z28, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bd
       cwd: /tmp/pip-install-jqj_z28y/mysqlclient/
  Complete output (31 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-3.6
  creating build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb
  copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb
  creating build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
  running build_ext
  building 'MySQLdb._mysql' extension
  creating build/temp.linux-x86_64-3.6
  creating build/temp.linux-x86_64-3.6/MySQLdb
  x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY6m -I/home/ubuntu/.virtualenvs/cai_django/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o
  x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,re-x86_64-3.6/MySQLdb/_mysql.o -lmysqlclient -lpthread -lz -lm -lrt -latomic -lssl -lcrypto -ldl -o build/lib.linux-x86_64-3.6/MySQLdb/_mysql.cpyth
  /usr/bin/ld: cannot find -lssl
  /usr/bin/ld: cannot find -lcrypto
  collect2: error: ld returned 1 exit status
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for mysqlclient
  Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
    Running setup.py install for mysqlclient ... error
    ERROR: Command errored out with exit status 1:
     command: /home/ubuntu/.virtualenvs/cai_django/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jqj_zze, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' all-headers /home/ubuntu/.virtualenvs/cai_django/include/site/python3.6/mysqlclient
         cwd: /tmp/pip-install-jqj_z28y/mysqlclient/
    Complete output (31 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-3.6
    creating build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb
    creating build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants
    running build_ext
    building 'MySQLdb._mysql' extension
    creating build/temp.linux-x86_64-3.6
    creating build/temp.linux-x86_64-3.6/MySQLdb
    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTI3.6m -I/home/ubuntu/.virtualenvs/cai_django/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o
    x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,ux-x86_64-3.6/MySQLdb/_mysql.o -lmysqlclient -lpthread -lz -lm -lrt -latomic -lssl -lcrypto -ldl -o build/lib.linux-x86_64-3.6/MySQLdb/_mysql.cpy
    /usr/bin/ld: cannot find -lssl
    /usr/bin/ld: cannot find -lcrypto
    collect2: error: ld returned 1 exit status
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /home/ubuntu/.virtualenvs/cai_django/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argvnt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cternally-managed --compile --install-headers /home/ubuntu/.virtualenvs/cai_django/include/site/python3.6/mysqlclient Check the logs for full com

The key point is ERROR: Failed Building Wheel for MysqlClient
The solution

sudo apt-get install python3 python-dev python3-dev
sudo apt-get install build-essential libssl-dev libffi-dev
sudo apt-get install libxml2-dev libxslt1-dev zlib1g-dev

Install it all again

pip3 install mysqlclient

The problem is solved.