時間:2023-05-29 03:27:02 | 來源:網站運營
時間:2023-05-29 03:27:02 來源:網站運營
【實戰(zhàn)演練】Python+Django網站開發(fā)系列03-Django初始配置與靜態(tài)Index頁面開發(fā):#本文歡迎轉載,轉載請注明出處和作者。django-admin startapp stumgr
自動創(chuàng)建了相關的app目錄,里面models.py與views.py是最重要的。INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stumgr',]
禁用CSRF跨站***阻止,在前面加#號。MIDDLEWARE =[#'django.middleware.csrf.CsrfViewMiddleware',]
修改templates的目錄,因為windows系統(tǒng)問題,需要將/替換為//,才能正常工作。templates是存放html靜態(tài)文件的默認位置。TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'.replace('//','/'))]
修改數據庫配置,原為DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
修改為(按照實際修改)DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'stumgr', 'HOST':'localhost', 'USER':'root', 'PASSWORD':'1qaz!QAZ', 'PORT':3306, }
最后settings最底下增加static目錄配置,這個是配置css、js等靜態(tài)文件的默認位置的。STATIC_URL = '/static/'STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'.replace('//','/')),)
到數據庫創(chuàng)建stumgr數據庫python manage.py makemigrations
如果已經提前安裝了mysqlclient,會順利進行,否則會報錯,提示 Error loading MySQLdb module。import pymysqlpymysql.install_as_MySQLdb()
【python3】pip install mysqlclient
并且創(chuàng)建工程的時候,需要勾選:python manage.py makemigrationspython manage.py migrate
提示數據庫表創(chuàng)建完成,查看數據庫,發(fā)現數據庫表已經自動創(chuàng)建成功。from django.conf.urls import url,includefrom django.contrib import adminurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('stumgr.urls')),]
然后再stumgr下面手動增加一個urls.py文件,將school下面的urls.py文件內容復制粘貼,再進行修改。from django.conf.urls import urlfrom stumgr.views import *urlpatterns = [ url(r'^$', index), url(r'^index/',index),]
然后編寫views.py,import的地方,使用默認的render,from django.shortcuts import render# Create your views here.def index(request): return render(request,'index.html')
runserver運行web服務。python manage.py runserver
打開瀏覽器訪問http://localhost:8000以及http://localhost:8000/index/嘗試,如果能夠成功訪問,則證明一切配置正常。<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>這是第一個HTML頁面</title></head><body><h1>這是我的網站大標題</h1><h2>這是我的網站子標題</h2><div> <p1>這是第一行內容</p1></div><div> <p2>這是第二行內容</p2></div><table border="1"> <tr> <th>第一列</th> <th>第二列</th> <th>第三列</th> </tr> <tr> <td> 1.1 </td> <td> 1.2 </td> <td> 1.3 </td> </tr></table><div><a href="/index/">跳轉到index</a></div><div><img src="/static/images/timg.jpg" width="640" height="480"></div></body></html>
其中<img>標簽中,需要將測試圖片放到/static/images/文件夾下,如果images文件夾不存在可以自行創(chuàng)建,文件名按照實際圖片名修改。urlpatterns = [ ...... url(r'^temp/', temp),]
2.2.3views添加函數def temp(request): return render(request,'temp.html')
2.2.4訪問測試關鍵詞:配置,靜態(tài),系列,實戰(zhàn)