DjangoORM常見問題及解決辦法


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即可

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM