問題
項目結構如下:
-
整個項目名為project
-
package1和package2是項目文件夾下的兩個文件夾,即兩個包(package)
-
兩個包中分別有init.py 和 module1.py / module2.py文件,其中module1.py和module2.py文件為兩個模塊(module)
(在python中一個*文件*可以被看成一個*獨立模塊*,而*包*對應着*文件夾*。區別包和文件夾的重要特征就是包文件夾內每一層目錄都有初始化文件__init__.py
)
原因:(不想看可直接跳到解決方法)
Python在啟動解釋器(Interpreter)時不光會導入環境變量中sys.path
發現的模塊,還會導入當前工作目錄下的模塊。
什么是環境變量中sys.path
發現的模塊和當前工作目錄下的模塊?
解決方法: 方法很簡單,就是把模塊路徑提供給解釋器:
(推薦) 把模塊路徑放到環境變量中作為全局變量(sys.path能掃描到)。
在module2.py開頭加入sys.path.append('../'):
import syssys.path.append('../') # 新加入的print(sys.path)from package1 import module1 module1.print_a('hello world')
sys.path.append()中添加的正是這個項目的項目目錄(*'../'表示當前目錄的父目錄,也即這個項目的項目目錄*)
2. NameError: name 'url' is not defined
c) 2019 Microsoft Corporation。保留所有權利。
(venv) D:\user\workspace\py_workspace\django_projecct\helloworld>python manage.py runserver
Performing system checks...
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001ABD8BCDF70>
Traceback (most recent call last):
File "D:\user\bin\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\management\base.py", line 376, in check
all_issues = self._run_checks(
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\user\bin\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "D:\user\bin\Python\Python38\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\user\bin\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\user\bin\Python\Python38\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\user\bin\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "D:\user\bin\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\user\workspace\py_workspace\django_projecct\helloworld\helloworld\urls.py", line 26, in <module>
url(r'^$',view.index)
NameError: name 'url' is not defined
嘗試導入:
from django.conf.urls import url
從django.contrib中導入管理 從django.urls導入路徑 從django.conf.urls入口導入
urlpatterns = [
'',
url(r'^ jet /',include('jet.urls','jet')),#Django JET URLS
url(r'^ admin /',include(admin.site.urls) ),
]`
3. ValueError: attempted relative import beyond top-level package
備注:使用命令行創建
使用命令行創建項目
django-admin startproject 項目名稱
使用 Pycharm 創建項目
file ---> new project ---- 選擇Django ---> 配置路徑和項目名稱 ---> 配置環境(默認用系統環境) ----> 點擊create(完成創建)
4.添加路徑
#第一種
os.path.join(BASE_DIR, 'templates')
#第二種
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
#第三種
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__path__)))
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))
5. 實用 | 安裝python模塊socket.timeout: The read operation timed out解決方案
1、使用pip安裝第三方庫過慢導致超時無法安裝:
pip install pandas
出現異常:
socket.timeout: The read operation timed out
2、 原因:
pip下載的時國外的資源,速度過慢,應該切換至國內鏡像
3、解決方法: 更換 pip 源自國內鏡像,在 pip install 后面添加 -i https://pypi.tuna.tsinghua.edu.cn/simple 上面藍色部分是鏡像地址,網上可以查到,這里提供兩個速度快的:
豆瓣:http://pypi.douban.com/simple/ 清華:https://pypi.tuna.tsinghua.edu.cn/simple
4、解決方法:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas
c:\user\bin\python\python38\python.exe -m pip --default-timeout=100 install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
6. 關於報錯:TemplateDoesNotExist (Django 3.1.2 Python 3.7)
提供幾個其他解決方法:
配置如下:
'DIRS': ["templates"]
'DIRS': [os.path.join(BASE_DIR, 'templates')]
'DIRS': [BASE_DIR / "templates", ]
如果pycharm報錯TemplateDoesNotExist ,問題則出現在
os.path.join(BASE_DIR, 'templates')
這一句的設置中,這一句話是指到“BASE_DIR/templates”文件夾中去取模板。通過debug跑到settings這句話可以發現BASE_DIR指定的其實是第一層的Hello World文件夾,而templates在第二層Hello World文件夾,所以一直提示錯誤。注意BASE_DIR是manage.py文件的所在路徑.
正確選擇如下:
os.path.join(BASE_DIR, 'HelloWorld/templates')
7.創建app
Django 規定,如果要使用模型,必須要創建一個 app。我們使用以下命令創建一個 TestModel 的 app:
django-admin.py startapp TestModel
在命令行中運行:
$ python3 manage.py migrate # 創建表結構
$ python3 manage.py makemigrations TestModel # 讓 Django 知道我們在我們的模型有一些變更
$ python3 manage.py migrate TestModel # 創建表結構
8. django 創建超級用戶
# python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@runoob.com
Password:
Password (again):
Superuser created successfully.
[root@solar HelloWorld]#
9. 一個 Contact 類可以有多個 Tag:
關聯 contact 外鍵時會報錯:TypeError: init() missing 1 required positional argument: 'on_delete'
解決辦法:
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
Django 在根據 models 生成數據庫表時報 init() missing 1 required positional argument: 'on_delete' 錯誤
原因:
在 django2.0 后,定義外鍵和一對一關系的時候需要加 on_delete 選項,此參數為了避免兩個表里的數據不一致問題,不然會報錯:TypeError: init() missing 1 required positional argument: 'on_delete'。
舉例說明:
user=models.OneToOneField(User)owner=models.ForeignKey(UserProfile)
需要改成:
user=models.OneToOneField(User,on_delete=models.CASCADE) --在老版本這個參數(models.CASCADE)是默認值
owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE) --在老版本這個參數(models.CASCADE)是默認值參數
說明:on_delete 有 CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET() 五個可選擇的值。
-
CASCADE:此值設置,是級聯刪除。
-
PROTECT:此值設置,是會報完整性錯誤。
-
SET_NULL:此值設置,會把外鍵設置為 null,前提是允許為 null。
-
SET_DEFAULT:此值設置,會把設置為外鍵的默認值。
-
SET():此值設置,會調用外面的值,可以是一個函數。一般情況下使用 CASCADE 就可以了。
10. 安裝 uwsgi 失敗
安裝 uwsgi 如果失敗,有可能是缺少Python的頭文件和靜態庫,需要安裝開發版本:
For apt (Ubuntu, Debian...):
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
For yum (CentOS, RHEL...):
sudo yum install python-devel
For dnf (Fedora...):
sudo dnf install python2-devel # for python2.x installs
sudo dnf install python3-devel # for python3.x installs
For zypper (openSUSE...):
sudo zypper in python-devel # for python2.x installs
sudo zypper in python3-devel # for python3.x installs
非多站模式時 vhost = true 和 no-site = true 需要注釋掉,否則后續 nginx 配置文件中設置的入口文件則不生效,服務器會回應 Internal Server error:
[uwsgi]
socket = 127.0.0.1:9090
master = true //主進程
#vhost = true //多站模式
#no-site = true //多站模式時不設置入口模塊和文件
workers = 2 //子進程數
reload-mercy = 10
vacuum = true //退出、重啟時清理文件
max-requests = 1000
limit-as = 512
buffer-size = 30000
pidfile = /var/run/uwsgi9090.pid //pid文件,用於下面的腳本啟動、停止該進程
daemonize = /website/uwsgi9090.log