django創建流程

安裝

pip3 install django

創建Django項目

  • django-admin startproject mysite(可以創建在任何目錄)
  • cd mysite(進入目錄)
  • python3 manage.py startapp blog 在項目中創建程序
  • python3 manage.py runserver 127.0.0.1:8080(運行服務端,如果不寫端口的話默認為8000)

檢查配置信息

在settings文件里面配置模板路徑

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

配置靜態文件目錄

  • 創建Python package包,命名為static
  • 然后根據static的位置配置靜態文件路徑
    STATIC_URL = '/static/'
    STATICFILES_DIRS = (
      os.path.join(BASE_DIR,'static'),
    )
  1. 數據庫配置

分別配置是使用sqlite3還是MySQL,默認配置為sqlite3

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

如果要設置MySQL為數據庫,進行如下設置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'books',    #你的數據庫名稱
        'USER': 'root',   #你的數據庫用戶名
        'PASSWORD': '', #你的數據庫密碼
        'HOST': '', #你的數據庫主機,留空默認為localhost
        'PORT': '3306', #你的數據庫端口
    }
}

添加應用

確保settings文件的INSTALLED_APPS目錄下有你的應用名稱

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bookmanage.apps.BookmanageConfig',
]

設計表關系 (數據庫)

在models.py 里面設計數據表 關系 ,使用語法使用orm語法來實現,比如要設計一個圖書的表

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.IntegerField()
    date = models.DateField()
    publish = models.CharField(max_length=32)
    author = models.CharField(max_length=32)
  • python3 manage.py makemigrations
    創建一個表(前提是在models.py里面已經寫好了orm)
    注意,在執行這條命令前先確保Django版本的Python已經安裝了模塊mysqlclient
    如果沒有,應該先執行pip3 install mysqlclient ,然后再執行以上語句
  • python3 manage.py migrate

添加路由(urls)

路徑的添加在urls這個文件中引入,需要注意的是,其中的語法,比如別名,數據提交,正則表達式

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^addbook/', views.addbook),
]

添加函數

函數的添加主要依靠的是request和HttpResponse,注意這兩個類的用法,

def index(request):
    return render(request, 'index.html')

而且函數里面涉及到給數據庫添加和提取數據,因此需要用到添加數據庫的方法,注意用models時的調用問題

from django.shortcuts import render, redirect
from bookmanage.models import *

def addbook(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish = request.POST.get('publish')
        auth = request.POST.get('auth')

        # 想數據庫里面插入數據
        Book.objects.create(
            title=title,
            price=price,
            date=date,
            publish=publish,
            auth=auth
        )
        return redirect('/index/')

    return render(request, 'addbook.html')

添加模板

添加模板一個是涉及靜態文件的引入,一個是設計模板語言,標簽渲染以及變量渲染和循環、判斷,里面有好多語法

{% load staticfiles %}   # 靜態文件的引入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
  # 通過使用別名來引入外部文件
    <link rel="stylesheet" href="{% static 'dist/css/bootstrap.css' %}">
</head>
<body>
     # a標簽的跳轉
    <a href="/addbook/"><button class="btn btn-primary">添加書籍</button></a>
    <table class="table table-striped">
        <tr>
            <th>編號</th>
            <th>姓名</th>
            <th>價格</th>
            <th>出版日期</th>
            <th>出版社</th>
            <th>作者</th>
        </tr>
    </table>
</body>
</html>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容