Django系列之第一個專案搭建
一、安裝
(1)使用pip3 install django在控制檯安裝django;
(2)新增到環境變數
二、建立專案
方式1:通過命令建立
(1)建立project: 通過django-admin.py startproject mysite: mysite為自己的專案名稱
C:\Users\XS\PycharmProjects>django-admin.py startproject MyFirstDjango C:\Users\XS\PycharmProjects\MyFirstDjango 的目錄 2018/11/05 16:53 <DIR> .2018/11/05 16:53 <DIR> .. 2018/11/05 16:53 560 manage.py 2018/11/05 16:53 <DIR> MyFirstDjango 1 個檔案 560 位元組 3 個目錄 8,265,093,120 可用位元組
(2)建立app: python manage.py startapp myApp : myApp為app名稱。注意:路徑要定位到MyFirstDjango下面再執行,不然找不到manage.py檔案。
C:\Users\XS\PycharmProjects\MyFirstDjango>python manage.py startapp mysite C:\Users\XS\PycharmProjects\MyFirstDjango 的目錄 2018/11/05 17:01 <DIR> . 2018/11/05 17:01 <DIR> .. 2018/11/05 16:53 560 manage.py 2018/11/05 17:01 <DIR> MyFirstDjango2018/11/05 17:01 <DIR> mysite 1 個檔案 560 位元組 4 個目錄 8,264,384,512 可用位元組
發現在MyFirstDjango檔案下面多了一個mysite的app資料夾。
方式2:通過pycharm開發工具建立
File->New Project->Django
建立好了目錄結構如下:
三、編寫流程
我們從瀏覽器發請求過來到服務端處理這個流程來梳理一下:
(1)請求url: 找到urls檔案,這裡的檔案路徑由我們自己定義,wsgi路由系統內部封裝了這裡配置的url進行迴圈迭代,然後執行url對應的view下的action。
from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ]
(2)執行專案: python manage.py runserver 8080,在瀏覽器中輸入http://127.0.0.1:8080/admin/檢視結果,這裡的admin後面會詳細講。
(3)建立資料表:開啟app下的models,所有的資料表對應的class都繼承了models.Model
from django.db import models # Create your models here. class UserInfo(models.Model): username=models.CharField(max_length=20) password=models.CharField(max_length=20) email=models.CharField(max_length=30)
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
執行python manage.py makemigrations啟動遷移,python manage.py migrate執行本次遷移。執行了這兩命令後我們可以發現在app資料夾下的migrations下多了遷移版本檔案。
# Generated by Django 2.1.3 on 2018-11-05 02:18 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UserInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=20)), ('password', models.CharField(max_length=20)), ('email', models.CharField(max_length=30)), ], ), ]
在後期開發中可能需要增加表格欄位,我們可以直接在models對應得類中新增欄位,如下
from django.db import models # Create your models here. class UserInfo(models.Model): username=models.CharField(max_length=20) password=models.CharField(max_length=20) email=models.CharField(max_length=30) phone=models.CharField(max_length=20)#增加欄位
僅僅這步操作是不會成功得,還需再次執行python manage.py makemigrations和python manage.py migrate才能遷移成功。每遷移一次在migrations資料夾下都會多一個遷移檔案
# Generated by Django 2.1.3 on 2018-11-05 06:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mysite', '0001_initial'), ] operations = [ migrations.AddField( model_name='userinfo', name='phone', field=models.CharField(default=1, max_length=20), preserve_default=False, ), ]
(4)做一個簡單增加,查詢功能
1、利用已經建立好的資料表UserInfo;
2、在全域性配置資料夾(MyFirstDjango資料夾下面得settings,urls和wsgi都是全域性得配置檔案)的urls檔案配置路由,如下:這裡可以使用path和url兩個配置路由,但是path不能使用正則匹配。
"""djtest3 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import url,include from mysite import views #注意:使用path的時候不能使用正則 urlpatterns = [ path('admin/', admin.site.urls), path(r'userinfo/',views.userinfo), ]
3、編寫路由對應的函式:在mysite下的views下建立如下:這裡包含兩個重要的類HttpRequest和HttpResponse,分別是用來封裝請求資訊和響應資訊的,在django架構下,HttpRequest已經封裝好了,我們只需要使用物件即可,下面的userinfo方法中的request就是
HttpRequest類的一個物件。
from django.shortcuts import render,HttpResponse from mysite import models # Create your views here. def userinfo(request): if request.method=="POST": username=request.POST.get("username") password=request.POST.get("password") email=request.POST.get("email") models.UserInfo.objects.create(username=username,password=password,email=email) user_list=models.UserInfo.objects.all() return render(request,"index.html",{"user_list":user_list})
HttpRequest的屬性和方法:
# path: 請求頁面的全路徑,不包括域名 # # method: 請求中使用的HTTP方法的字串表示。全大寫表示。例如 # # if req.method=="GET": # # do_something() # # elseif req.method=="POST": # # do_something_else() # # GET: 包含所有HTTP GET引數的類字典物件 # # POST: 包含所有HTTP POST引數的類字典物件 # # 伺服器收到空的POST請求的情況也是可能發生的,也就是說,表單form通過 # HTTP POST方法提交請求,但是表單中可能沒有資料,因此不能使用 # if req.POST來判斷是否使用了HTTP POST 方法;應該使用 if req.method=="POST" # # # # COOKIES: 包含所有cookies的標準Python字典物件;keys和values都是字串。 # # FILES: 包含所有上傳檔案的類字典物件;FILES中的每一個Key都是<input type="file" name="" />標籤中 name屬性的值,FILES中的每一個value同時也是一個標準的python字典物件,包含下面三個Keys: # # filename: 上傳檔名,用字串表示 # content_type: 上傳檔案的Content Type # content: 上傳檔案的原始內容 # # # user: 是一個django.contrib.auth.models.User物件,代表當前登陸的使用者。如果訪問使用者當前 # 沒有登陸,user將被初始化為django.contrib.auth.models.AnonymousUser的例項。你 # 可以通過user的is_authenticated()方法來辨別使用者是否登陸: # if req.user.is_authenticated();只有啟用Django中的AuthenticationMiddleware # 時該屬性才可用 # # session: 唯一可讀寫的屬性,代表當前會話的字典物件;自己有啟用Django中的session支援時該屬性才可用。
在django架構下面,響應內容是需要我們自己編寫的,HttpResponse下主要有三種響應的形式:
1)直接使用HttpResponse返回字串或者html字串,這種形式不包含python模板渲染;
2)render: render(request, template_name, context=None, content_type=None, status=None, using=None),可以向模板傳送資料,渲染成瀏覽器能夠解析的html檔案;
3)redirect:跳轉到檢視方法。
render與redirect的區別:render只是返回模板的html內容,不會重定向,不會改變重新整理後的url;redirect會走路由然後執行路由對應方法,最終的url和路由的url對應。
4、模板檔案index.html:在全域性模板templates下面新建index.html。{% %}和{{ }}是python模板的語法,用來渲染後臺傳過來的資料。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/userinfo/" method="post"> 使用者名稱:<input type="text" name="username"> 密碼:<input type="text" name="password"> 郵箱:<input type="text" name="email"> <input type="submit" value="提交"> </form> <hr> <h1 id="usr">使用者資訊</h1> <table border="1"> <thead> <tr> <td>使用者名稱</td> <td>密碼</td> <td>郵箱</td> </tr> </thead> <tbody> {% for item in user_list %} <tr> <td>{{ item.username }}</td> <td>{{ item.password }}</td> <td>{{ item.email }}</td> </tr> {% endfor %} </tbody> </table> <script src="/static/jQuery/jquery-1.10.2.min.js"></script> <script> $('#usr').css('color','red') </script> </body> </html>
5、執行專案:在終端中輸入 python manage.py runserver 8089,然後再瀏覽器中訪問http://127.0.0.1:8089/mysite/userinfo/,可以看到頁面,第一個django專案執行起來了。
參考文件: https://www.cnblogs.com/yuanchenqi/articles/6083427.html