自动秒收录

python代码大全 (Python中Django框架使用总结)


文章编号:934 / 更新时间:2023-11-09 01:55:20 / 浏览:
Python

【1】建立应用

① 建立应用

命令:

python manage.py startapp 应用名


其会生成如下文件:


admin.py :管理站点模型的声明文件,默认为空。


apps.py :应用信息定义文件。在其中生成了类Appconfig,类用于定义应用名等Meta数据。


migrations : 用于在之后定义引用迁移功能。


models.py : 添加模型层数据类的文件。


test.py :测试代码文件。


views.py :定义URL响应函数。如果遇到错误如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 makemigrations
python manage.py migrate

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

【2】Xadmin使用

官网地址:http://sshwsfc.github.io/xadmin/

GitHub地址:https://github.com/sshwsfc/xadmin


下载源码包压缩文件之后,我们可以解压这个压缩文件,获取到源码包。


① 将下载好的xadmin解压,复制里面的xadmin文件夹到我们的项目根目录当中


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

③ 将extra_apps mark为root_source


④ 将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.1django-formtools==2.1,否则版本太低,拉不起来。


pip install -r requirements.txt -ihttps://pypi.douban.com/simple/,这个需要在requirements.txt文件的当前路径下哦。

pip  install  -r  requirements.txt   -i  https://pypi.douban.com/simple/

⑥ 将xadmincrispy_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注释掉改为我们xadminurl(r'^xadmin/', xadmin.site.urls),

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

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


这里需要说明的是,我这里是将xadmin解压到了python安装目录的Lib下面,并在如下路径下执行操作命令pip install -r requirements.txt -ihttps://pypi.douban.com/simple/


【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.CASCADE
cityinfo = 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报错TypeError: 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_text
ImportError: cannot import name 'python_2_unicode_compatible'

修改为:

from six import python_2_unicode_compatible
from django.utils.encoding import smart_text

⑦ cannot import name 'pretty_name’

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

修改为:

from django.forms import forms


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

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

修改为:

from django.templatetags.static import static


⑨ cannot import name 'login’

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


修改为:

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


⑩cannot import name 'FieldDoesNotExist’


  from django.db.models.fields import FieldDoesNotExist
ImportError: 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_TERMS
ImportError: 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_storage
ModuleNotFoundError: No module named 'django.contrib.formtools'

解决:

# 卸载旧版本
pip uninstall django-formtools
# 安装新版本
pip install django-formtools
 from django.contrib.auth.views import password_reset_confirm
ImportError: cannot import name 'password_reset_confirm'

修改:

from django.contrib.auth.views import PasswordResetForm

(14) AttributeError: ‘Settings’ object has no attribute 'MIDDLEWARE_CLASSES’


修改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:
• 1

(15) cannot import name 'DEFAULT_FORMATS’



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

修改:

from import_export.formats.base_formats import DEFAULT_FORMATS
from 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_list
admin_modify
admin_urls
cache
crispy_forms_field
crispy_forms_filters
crispy_forms_tags
crispy_forms_utils
i18n
l10n
log
static
tz
xadmin_tags


解决:

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



相关标签: 数据库Python

本文地址:https://www.0558.la/article/c46947117de982dc313b.html

上一篇:eclipse左侧项目栏不见了Eclipse如何从导入...
下一篇:新注册的域名多久可以备案新注册的域名要如...

温馨提示

做上本站友情链接,在您站上点击一次,即可自动收录并自动排在本站第一位!
<a href="https://www.0558.la/" target="_blank">自动秒收录</a>