Python中Django框架使用总结(python之django框架前端与后端的结合)

网友投稿 919 2022-08-30


Python中Django框架使用总结(python之django框架前端与后端的结合)

【1】建立应用

① 建立应用

命令:

python manage.py startapp 应用名

其会生成如下文件:

如果遇到错误如​​No module named 'users'​​,那么首先检测路径、包名是否有问题,然后检测是否在项目的settings.py中INSTALLED_APPS配置了我们的users。最后一定记得下面这行命令哦

#将我们自己定义的包加入到python搜寻环境变量当中sys.path.insert(0,os.path.join(BASE_DIR,'apps'))

② 迁移同步

在修改完models.py中的字段,需要对数据表中结构进行修改的时候,在终端中执行以下迁移命令即可。

python manage.py makemigrationspython manage.py migrate

什么是迁移?把模型转化为对数据库的操作,这就是迁移

【2】Xadmin使用

官网地址:​​GitHub地址:​​将下载好的xadmin解压,复制里面的xadmin文件夹到我们的项目根目录当中

② 创建extra_apps放置第三方的app,将xadmin移动到我们这个extra_apps下

④ 将extra_apps在setting当中配置好搜索路径

#将我们自己定义的包加入到python搜寻环境变量当中sys.path.insert(0,os.path.join(BASE_DIR,'apps'))sys.path.insert(0,os.path.join(BASE_DIR,'extra_apps'))

⑤ 打开cmd,进入虚拟环境,安装xadmin依赖包,依赖包的版本在xadmin文件夹下:requirements.txt,在其中有一个包版本改成2.1 ​​django-formtools==2.1​​,否则版本太低,拉不起来。

​​pip install -r requirements.txt -i install -r requirements.txt -i 将​​xadmin​​​和​​crispy_forms​​​添加到我们的​​installed_apps​​

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'courses.apps.CoursesConfig', 'orgs.apps.OrgsConfig', 'operations.apps.OperationsConfig', 'xadmin', 'crispy_forms', 'captcha', 'DjangoUeditor',]

⑦ urls.py文件中将我们本来的admin注释掉改为我们xadmin ​​url(r'^xadmin/', xadmin.site.urls),​​

⑧ 再次执行迁移同步,目的是为了生成xadmin所依赖的表

最后创建超级管理员,去验证xadmin是否安装成功。

【3】一些错误

① No module named ‘widgets’

DjangoUeditor是基于Python 2.7的,对Python3的支持有问题。导致widgets.py文件出错,不能import。解决方法为修改widgets.py或者采用网上修改好的版DjangoUeditor3。

github搜DjangoUeditor3,​​github地址​​​克隆到本地,复制文件夹里面的DjangoUeditor文件夹,放到虚拟环境下​​python3/Lib/site-packages/​​文件夹下,或者直接放在你的Django项目下。

最后记得重启Django

python manage.py runserver

② ​​__init__() missing 1 required positional argument: 'on_delete'​​

在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:

# 添加on_delete=models.CASCADEcityinfo = models.ForeignKey(CityInfo,verbose_name="所在城市",on_delete=models.CASCADE)

on_delete有​​CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()​​五个可选择的值

CASCADE:此值设置,是级联删除。PROTECT:此值设置,是会报完整性错误。SET_NULL:此值设置,会把外键设置为null,前提是允许为null。SET_DEFAULT:此值设置,会把设置为外键的默认值。SET():此值设置,会调用外面的值,可以是一个函数。

③ cannot import name ‘six’ from 'django.utils’

pip install six

然后进入python安装目录下的site-packages,将six.py 复制到 django/utils即可。

或者降低版本:​​pip install django==2.2.6​​

或者修改

from django.utils import six # 修改为import six

④ No module named 'django.core.urlresolvers’ django2.0 把原来的 ​​​django.core.urlresolvers​​ 包 更改为了 django.urls包,所以我们需要把导入的包都修改一下就可以了。

即修改为如下:

from django.urls import NoReverseMatch, reverse

⑤ dashboard.py报错T​​ypeError: init() takes 1 positional argument but 6 were given​​

# 原始forms.Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs)# 修改为forms.Field.__init__(self)

⑥ ​​cannot import name 'python_2_unicode_compatible'​​

from django.utils.encoding import python_2_unicode_compatible, smart_textImportError: cannot import name 'python_2_unicode_compatible'

修改为:

from six import python_2_unicode_compatiblefrom django.utils.encoding import smart_text

⑦ cannot import name 'pretty_name’

from django.forms.forms import pretty_nameImportError: cannot import name 'pretty_name'

修改为:

from django.forms import forms

⑧ No module named 'django.contrib.staticfiles.templatetags’

from django.contrib.staticfiles.templatetags.staticfiles import staticModuleNotFoundError: No module named 'django.contrib.staticfiles.templatetags'

修改为:

from django.templatetags.static import static

⑨ cannot import name 'login’

from django.contrib.auth.views import loginImportError: cannot import name 'login'

修改为:

from django.contrib.auth import authenticate, login, logout

⑩cannot import name 'FieldDoesNotExist’

from django.db.models.fields import FieldDoesNotExistImportError: cannot import name 'FieldDoesNotExist'

修改为:

from django.core.exceptions import FieldDoesNotExist

(11)cannot import name 'QUERY_TERMS’

from django.db.models.sql.query import LOOKUP_SEP, QUERY_TERMSImportError: cannot import name 'QUERY_TERMS'

修改为:

from django.db.models.sql.query import LOOKUP_SEP, Query

(12)No module named 'django.contrib.formtools’

from django.contrib.formtools.wizard.storage import get_storageModuleNotFoundError: No module named 'django.contrib.formtools'

解决:

# 卸载旧版本pip uninstall django-formtools # 安装新版本pip install django-formtools

(13) cannot import name 'password_reset_confirm’

from django.contrib.auth.views import password_reset_confirmImportError: cannot import name 'password_reset_confirm'

修改:

from django.contrib.auth.views import PasswordResetForm

修改​​xadmin\plugins\language.py", line 24,​​将

if settings.LANGUAGES and 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE_CLASSES:

修改为:

if settings.LANGUAGES and 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE:

(15) cannot import name 'DEFAULT_FORMATS’

from import_export.admin import DEFAULT_FORMATS, SKIP_ADMIN_LOG, TMP_STORAGE_CLASSImportError: cannot import name 'DEFAULT_FORMATS'

修改:

from import_export.formats.base_formats import DEFAULT_FORMATSfrom import_export.admin import ImportMixin

(16) No module named 'django_redis’

Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis'

解决:

pip install django_redis

(17) 'Specifying a namespace in include() without providing an app_name '

Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

# 原先格式url(r'^users/',include('users.urls',namespace='users')),# 修改后格式url(r'^users/',include(('users.urls',"users"),namespace='users')),

(18) django.db.models.AutoField

xadmin.UserWidget: (models.W042) Auto-created primary key used when not defining a primary key type, by default ‘django.db.models.AutoField’.

HINT: Configure the DEFAULT_AUTO_FIELD setting or the XAdminConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. ‘django.db.models .BigAutoField’.

settings文件添加如下内容:

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

(19) 自定义错误页面

?: (urls.E007) The custom handler404 view ‘users.views.handler_404’ does not take the correct number of arguments (request, exception).

原始配置:

handler404 = 'users.views.handler_404'handler500 = 'users.views.handler_500'def handler_404(request): return render(request,'handler_404.html')def handler_500(request): return render(request,'handler_500.html')

修改函数为如下:

def handler_404(request,exception=None): return render(request,'handler_404.html',status=404)def handler_500(request,exception=None): return render(request,'handler_500.html',status=500)

(20) ‘staticfiles’ is not a registered tag library. Must be one of:

'staticfiles' is not a registered tag library. Must be one of:admin_listadmin_modifyadmin_urlscachecrispy_forms_fieldcrispy_forms_filterscrispy_forms_tagscrispy_forms_utilsi18nl10nlogstatictzxadmin_tags

解决:

{% load staticfiles %}改成{% load static %}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python copy and deeepcopy(python下载安装教程)
下一篇:java文件读写操作实例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~