Djanjo 的app 模板路徑 靜態檔案 完整版登入 新手三件套 以及orm
一: django中app的概念:
一個專案可以包含多個應用(app,類似於模組,主頁開啟多個模組就是多個app)
建立了app,要在配置檔案中註冊
二:模板路徑配置:
1 templates資料夾
2 settings裡註冊一下
三:靜態檔案配置
1 STATIC_URL = '/static/' 一般不需要改動
2 建立一個static的資料夾
3 STATICEFILES_DIRS=[
os.path.join(BASE_DIR,'static'),建立的資料夾路徑(可以寫多個)
]_
四:完整版登入功能
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url('login',views.login ), ]url.py
from django.shortcuts import render, HttpResponse import pymysql # Create your views here.viewdef login(request): if request.method == "GET": return render(request, 'login.html') elif request.method == "POST": print(request.POST) name = request.POST.get('name') pwd = request.POST.get('pwd') # 連結資料庫 conn = pymysql.connect(host='127.0.0.1', port=3306, db='andy', user='root', password='admin') cur = conn.cursor() cur.execute('select * from user where name=%s and password=%s ', [name, pwd]) user = cur.fetchone() if user: return HttpResponse("登入成功") else: return HttpResponse("登入失敗")
""" Django settings for day71login project. Generated by 'django-admin startproject' using Django 1.11.9. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*#^ssm!6iblsg&vm#b5133_u4a4j-ngov!i+*9p3n*4n^[email protected]&(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ] 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', ] ROOT_URLCONF = 'day71login.urls' 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', ], }, }, ] WSGI_APPLICATION = 'day71login.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static'), # os.path.join(BASE_DIR, 'static3'), ]settings
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"> <link rel="stylesheet" href="/static/css/mycss.css"> <title>登入</title> </head> <body> <h1>登入</h1> <div class="col-md-6 col-md-offset-3"> <form action="/login2/" method="post"> <p>使用者名稱:<input type="text" name="name" class="form-control"></p> <p > 密碼:<input type="password" name="pwd" class="form-control"> </p> {# type是button,不會往後臺提交資料 #} {# <input type="button" value="提交">#} {# 這兩種會往後臺提交資料#} <input type="submit" value="提交"> {# <button>提交</button>#} </form> </div> </body> </html>templates/login.html
h1{
color: red;
}
mycss.css
1 login.html
***重點***1 action:提交到後臺的地址三種寫法:
1 http://127.0.0.1:8000/login
2 /login/ 推薦用
3 空
2 method post方式
3 <input type="submit" value="提交">或<button></button>
type不可以是button
<form action="http://127.0.0.1:8000/login" method="post">
<p>使用者名稱:<input type="text" name="name" class="form-control"></p>
<p >
密碼:<input type="password" name="pwd" class="form-control">
</p>
<input type="submit" value="提交">
</form>
2 檢視層:
1 request.method ----前臺提交過來請求的方式
2 request.POST(相當於字典)----post形式提交過來的資料,(http請求報文的請求體重)
3 request.POST.get('name') ----推薦用get取值(取出列表最後一個值)
4 request.POST.getlist('name')-----取出列表所有的值_
5 前臺get方式提交的資料,從request.GET字典裡取
3 連結資料庫(防止注入,推薦以下寫法)
cur.execute('select * from user where name=%s and password=%s ',[name,pwd])
五: get請求和post請求
get:獲取資料,頁面,攜帶資料是不重要的資料(資料量有大小限制)
post:往後臺提交資料
六: 新手三件套總結
1 render--返回頁面
預設會去templates裡找,注意路徑
2 redirect--重定向
3 HttpResponse
本質:都是返回HttpResponse的物件
三件套小結 :render Httpresponse redirect
它核心的三件套是必須要掌握的,一切的功能都是基於這三者來實現的, Httpresponse,--負責來響應瀏覽器的,需要瀏覽器返回什麼就在它裡面定義什麼即可,瀏覽器的根本就是返回字串,所以Httpresponse("str(ok)")這樣寫就可以 render, --負責接收request引數,然後還有一個渲染的頁面(也就是一個HTML標籤),以及儲存資料用的一個字典資料型別的引數.這個render主要的功能就是渲染頁面,在渲染的同時我們需要把一些引數填充到所渲染的頁面裡面去,就需要用到這個render功能,[那我們什麼時候需要使用到引數去填充頁面的情況呢,我們的頁面是提前寫好的,那是前端的時候,現在我們需要跟後端進行一些互動,這個時候前端顯示的資料就會有所調整,根據特殊的要求來進行調整,這個時候我們的程式碼就需要後端來實現了,把後端改好的程式碼填充到前端去,就需要把前端的頁面設定一塊地方用來預存引數,當我的後端需要改變功能的時候可以啟動到前端預存的那些引數然後進行修改,這個時候就需要使用到填充引數到所渲染的頁面中去] redirect,--負責跳轉頁面,後端的程式碼塊碼完之後我們想讓頁面往何處跳轉就使用它去跳轉,return redirect("/sogo/") 這裡就是跳轉的頁面,之所以這樣寫,是因為我們的url域名裡面都是這樣的格式,https://i.cnblogs.com/EditPosts.aspx?postid=8269914,例如這裡的http後面的域名就是這樣的格式, 這裡還有一個很重要的點就是request,它是一個引數,是我們在django裡面寫函式的時候需要傳入的引數,這個引數是幹什麼用的呢,它裡面包裹了大量的資訊,都是關於請求的資料資訊, 所有跟請求相關的資料都是由它來進行接收,我們的形參就是用來接收各種的引數的,它就是那樣的一個形參,它只是接收跟請求相關的引數,我們以後會學到它的大量的用法,包括都有哪些是跟請求相關的,請求都是有哪些,等等.
七:orm
1 orm簡介:
查詢資料層次圖解:如果操作mysql,ORM是在pymysq之上又進行了一層封裝
- MVC或者MTV框架中包括一個重要的部分,就是ORM,它實現了資料模型與資料庫的解耦,即資料模型的設計不需要依賴於特定的資料庫,通過簡單的配置就可以輕鬆更換資料庫,這極大的減輕了開發人員的工作量,不需要面對因資料庫變更而導致的無效勞動
- ORM是“物件-關係-對映”的簡稱。
2 orm示例如下
#sql中的表 #建立表: CREATE TABLE employee( id INT PRIMARY KEY auto_increment , name VARCHAR (20), gender BIT default 1, birthday DATA , department VARCHAR (20), salary DECIMAL (8,2) unsigned, ); #sql中的表紀錄 #新增一條表紀錄: INSERT employee (name,gender,birthday,salary,department) VALUES ("alex",1,"1985-12-12",8000,"保潔部"); #查詢一條表紀錄: SELECT * FROM employee WHERE age=24; #更新一條表紀錄: UPDATE employee SET birthday="1989-10-24" WHERE id=1; #刪除一條表紀錄: DELETE FROM employee WHERE name="alex" #python的類 class Employee(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=32) gender=models.BooleanField() birthday=models.DateField() department=models.CharField(max_length=32) salary=models.DecimalField(max_digits=8,decimal_places=2) #python的類物件 #新增一條表紀錄: emp=Employee(name="alex",gender=True,birthday="1985-12-12",epartment="保潔部") emp.save() #查詢一條表紀錄: Employee.objects.filter(age=24) #更新一條表紀錄: Employee.objects.filter(id=1).update(birthday="1989-10-24") #刪除一條表紀錄: Employee.objects.filter(name="alex").delete()