码迷,mamicode.com
首页 > 其他好文 > 详细

DjangoORM常见问题及解决办法

时间:2020-05-27 12:16:42      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:mys   引擎   man   classes   数据   cat   each   参数   after   

1.Django默认支持sqlite数据库

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

若要建立MySQL数据库,需更改settings配置文件

DATABASES = {

    ‘default‘: {

        ‘ENGINE‘: ‘django.db.backends.mysql‘,

        ‘NAME‘: ‘Django_ORM‘,    #数据库名称

        ‘USER‘: ‘root‘,   #数据库用户名

        ‘PASSWORD‘: ‘******‘, #数据库密码

        ‘HOST‘: ‘‘, #数据库主机,留空默认为localhost

        ‘PORT‘: ‘3306‘, #数据库端口
    }}

 同时在项目文件中的__init__.py文件中添加以下代码:

import pymysql
pymysql.install_as_MySQLdb()  #驱动引擎提换成pymysql

执行:

python manage.py makemigrations

若出现在以下情况,创建未成功,这个是Django对MySQLdb版本的限制,我们使用的是PyMySQL造成的。

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required;
you have 0.9.3.

需更改base.py文件如下即可。这里我用的是aconda配置的环境,路径为:D:\conda\Lib\site-packages\Django-3.0.6-py3.7.egg\django\db\backends\mysql

version = Database.version_info
if version < (1, 3, 13):
    #raise ImproperlyConfigured(‘mysqlclient 1.3.13 or newer is required; you have %s.‘ % Database.__version__)
    pass

 2.Pycharm连接MYSQL问题,服务器返回无效时区。进入“高级”选项卡,手动设置“serverTimezone”属性。

 Server returns invalid timezone. Go to ‘Advanced‘ tab and set ‘serverTimezone‘ property manually. 

解决办法:  在dos界面输入mysql -hlocalhost -uroot -p回车输入密码

         继续输入 show variables like‘%time_zone‘;回车

       set global time_zone = ‘+8:00‘; 回车

重新连接即可。

 

3.重启数据库时,提示:Server returns invalid timezone. Go to ‘Advanced‘ tab and set ‘serverTimezone‘ property manually.

解决办法:在DOS界面进入自己的Mysql,输入以下指令即可。

set global time_zone=‘+8:00‘;

 

4. 外键操作:TypeError: __init__() missing 1 required positional argument: ‘on_delete‘

 

publish = models.ForeignKey("Publish")

 

属性操作:

  CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
  PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
  SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
  SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
  SET(): 自定义一个值,该值当然只能是对应的实体了

解决办法:添加属性

publish = models.ForeignKey("Publish",on_delete=models.CASCADE)

5.Django2.0以上,路由正则需调用re_path

from django.contrib import admin
from django.urls import path,re_path

from blog import views

urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘showtime/‘, views.showtime),
    re_path(‘article/(?P<year>\d{4})/(?P<month>\d{2})‘, views.a), #有名命名,view内函数参数必须为命名好的形参
]

 6.post请求403Forbidden错误,这是Django的一个安全机制引起的

Forbidden (403)
CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.

Help
Reason given for failure:

    CSRF cookie not set.
    
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django‘s CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

Your browser is accepting cookies.
The view function passes a request to the template‘s render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You‘re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

解决办法:将settings中间件csrf暂时引掉或者在form表单最后添加{% csrf_token %},建议使用后者

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    #‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]

 7.Pycharm views request没有自动提示session,可能是由于版本问题。

解决方法:在settings中间件MIDDLEWARE修改为MIDDLEWARE_CLASSES即可

 

DjangoORM常见问题及解决办法

标签:mys   引擎   man   classes   数据   cat   each   参数   after   

原文地址:https://www.cnblogs.com/chouchoudedahuilang/p/12971534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!