views.pyhtml
from django.shortcuts import render from django.http import HttpResponse import random # Create your views here. numbers = random.randint(1, 101) class People(object): def __init__(self, name, age, phone): self.name = name self.age = age self.phone = phone def index(request): print(request) people = People('李四', 25, 1111) data = { 'name': '張三', 'age': 22, 'numbers': [x for x in range(0, 30) if x % 2 == 0], 'dictData': {'city': '鄭州', 'weather': '晴天'}, 'people': people } return render(request, 'index.html', data) def login(request): print(request) # 判斷是get 請求 仍是post 請求 if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': # # ID = request.POST.get('id', default='') pwd = request.POST.get('pwd', default='') if ID == '123456789' and pwd == '123456': return HttpResponse('登陸成功') else: return render(request, 'login.html', {'error': '密碼錯誤'}) # 定義主頁的視圖函數 def guess_num(request): result = '' # 判斷當前請求的 是get /post # 設置全局變量 global numbers if request.method == 'POST': # 從post 請求中提取傳遞過來的參數 gus_num = request.POST.get('gus_num', default='0') if gus_num == '': result = '請從新輸入,數字不能爲空' else: if int(gus_num) < numbers: result = '猜小了' elif int(gus_num) > numbers: result = '猜大了' else: result = '猜對了,答案已重置,請繼續' numbers = random.randint(0,101) names = ['小紅', '小明', '小李', '小王', '小花'] data = { 'name': random.choice(names), 'age': random.randint(18, 23), # 返回的是一個列表,startswith () 是以什麼開頭的 'names': [name for name in names if name.startswith('小')], 'phone': 13213, 'result': result } # data 就是箱模板傳遞參數 return render(request, 'guess_num.html', data)
settings.pypython
""" Django settings for django_demo4 project. Generated by 'django-admin startproject' using Django 1.11.5. 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 = 'l&nmv@o_n_g3#k!0lf^0y#3qzb$j7-9hushlmdoup*erbnk1=c' # 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', 'app' ] 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 = 'django_demo4.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 = 'django_demo4.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/'
urls.pysql
"""django_demo4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from app import views urlpatterns = [ url(r'^index',views.index), url(r'^guess',views.guess_num), url(r'^login',views.login), url(r'^admin/', admin.site.urls), ]
guess_num.htmldjango
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>猜數字首頁</title> <style> nav{ text-align: center; color: mediumaquamarine; font-family: 楷體; } main{ position: relative; width: 100%; } main>div{ width: 600px; margin:0 auto; text-align: center; } </style> </head> <body> <nav> {# {{ 取傳遞過來的變量的值 }} #} <h3>歡迎{{ name }}來猜數字遊戲</h3> <h3>年齡: {{ age }}</h3> <h3>電話: {{ phone }}</h3> {# 模板中的for循環 #} {% for name in names %} {# 取出列表中的每個元素 #} <h3>{{ name }}</h3> {# endfor 表示for 循環結束 #} {% endfor %} </nav> <main> <div> {# action 表單提交的路由地址 method 指定提交的方式 默認get #} <form action="/guess/" method="post"> {# csrf_token 提交token 驗證 #} {% csrf_token %} {# placeholder 佔位字符 name 表單數據對應的key#} <input name="gus_num" type="text" placeholder="請輸入你猜的數字"><br> <button type="submit">提交</button> </form> <h3>{{ result }}</h3> </div> </main> </body> </html>
index.htmlsession
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板參數傳遞</title> </head> <body> <h1>{{ name }}</h1> <h1>{{ age }}</h1> {# for 循環遍歷列表 ,取出每個值 #} <ul> {# 每執行一次for循環,都會新建一個li標籤 #} {% for num in numbers %} {# 每次for 循環,都會新建一個li標籤 #} {# forloop.counter(從1開始) counter0(從0開始) 記錄循環的次數 .first判斷是否爲列表的第一個元素#} {# if 能夠判斷某些條件是否成立 #} {% if forloop.first %} <li>這是第一個元素</li> {% elif forloop.last %} <li>這是最後一個元素</li> {% else %} <li>{{ num }}</li> {% endif %} <li>{{ forloop.counter}}</li> {% endfor %} </ul> {#使用if 判斷某個參數是否存在 #} {% if dictData %} <h1>dictData這個參數</h1> <h3>{{ dictData.city }}</h3> <h3>{{ dictData.weather }}</h3> {% else %} <h1>沒有dictData這個參數</h1> {% endif %} {# 穿過來的是自定義對象,直接經過,屬性獲取屬性值 #} <h1> {{poeple.name }}</h1> <h1> {{people.age }}</h1> <h1> {{people.phone }}</h1> {# 填寫要訪問的路由 #} <a href="/login/">點擊登陸</a> </body> </html>
login.htmlapp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>銀行卡登陸頁面</title> </head> <body> <div>填寫完點擊登陸</div> <form action="/login/" method="post"> {# csrf_token驗證 #} {% csrf_token %} <input name="id" type="text" placeholder="請輸入銀行卡號"> <input name="pwd" type="password" placeholder="請輸入取款密碼"> <button type="submit">點擊登陸 </button> {% if error %} <h1>{{ error }}</h1> {% endif %} </form> </body> </html>