导航

Django常见问题集锦

Posted on 2021-03-08 09:32  Young哥哥  阅读(1052)  评论(0编辑  收藏  举报

1. 解决pycharm终端/cmd运行python脚本报错“ImportError/ModuleNotFoundError:No Module named ...”

问题

项目结构如下:

img

  • 整个项目名为project

  • package1和package2是项目文件夹下的两个文件夹,即两个包(package)

  • 两个包中分别有init.py 和 module1.py / module2.py文件,其中module1.py和module2.py文件为两个模块(module)

(在python中一个*文件*可以被看成一个*独立模块*,而**对应着*文件夹*。区别包和文件夹的重要特征就是包文件夹内每一层目录都有初始化文件__init__.py

原因:(不想看可直接跳到解决方法)

Python在启动解释器(Interpreter)时不光会导入环境变量中sys.path发现的模块,还会导入当前工作目录下的模块。

什么是环境变量中sys.path发现的模块和当前工作目录下的模块?

当你在IDE中启动解释器时,当前的工作目录就是项目目录,能顺利调用同项目中的模块;但是当你通过命令行启动时,当前工作目录为你启动解释器时所在的目录,如果当时的位置不是项目目录,那么项目目录中的模块就不会被找到,因此运行的时候报错:ModuleNotFoundError: No Module named ...(在例子中我的当前目录是.../package2是项目目录底下的一个文件夹,不是项目目录,所以报错)

解决方法: 方法很简单,就是把模块路径提供给解释器:
(推荐) 把模块路径放到环境变量中作为全局变量(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 = trueno-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