PythonWeb_Django_03_bj

1、模板
1、变量(略)
2、标签
1、什么是标签
允许将服务器端的功能嵌入到模板中
2、语法
{% 标签内容 %}
3、常用标签
1、for
1、语法
{% for 变量 in 列表|元组|字典 %}

{{变量}}


{{变量.方法}}


{{变量.属性}}


{% endfor %}

				允许使用内置变量 - forloop 获取循环的信息
					forloop在{%for%}中是免声明就可以直接使用的
					forloop.counter : 获取当前循环的次数
					forloop.counter0: 获取当前循环的下标
					forloop.first : 是否为第一次循环
					forloop.last : 是否为最后一次循环
		2、if
			1、if 标签
				语法:
					{% if 条件 %}
						满足条件时要运行的内容
					{% endif %}
			2、if ... else ... 标签
				语法:
					{% if 条件 %}
						满足条件时要执行的操作
					{% else %}
						不满足条件时要执行的操作
					{% endif %}
			3、if ... elif ... else
				语法:
					{% if 条件1 %}
						满足条件1运行的内容
					{% elif 条件2 %}
						满足条件2运行的内容
					{% else %}
						以上条件都不满足时运行的内容
					{% endif %}
3、过滤器
	1、作用
		在显示变量的数据之前,允许对数据进行筛选或改变
	2、过滤器的语法
		{{变量|过滤器}}
	3、常用过滤器
		1、{{value|upper}}
			将value变为大写字符输出
		2、{{value|lower}}
			将value变为小写字符输出
		3、{{value|floatformat:n}}
			将value四舍五入到 n 位小数
		4、{{value|truncatechars:n}}
			将字符串截取到n位字符(包含...)
4、	url()中的name参数
	url(regex,views,kwargs=None,name=None)
		name:允许为当前的url设置别名,可以在Template中使用别名
        找到对应的url
	语法:
		url(regex,views,name="别名")
		在模板中使用别名找到对应的url
			{% url '别名' %}
5、静态文件
	1、什么是静态文件
		不与用户发生动态交互的文件,称为静态文件
		如:css,js,image,audio,video,html
	2、Django中静态文件的处理
		需要在settings.py中设置静态文件的访问路径 和 存储路径
		1、访问路径
			STATIC_URL='/static/'

			作用:
				当访问路径是 localhost:8000/static/****
				一律去静态文件存储路径中搜索静态文件
		2、存储路径
			STATICFILES_DIRS=(BASE_DIR,'静态目录名称')

			在项目中以及各个应用中,都可以创建对应名称一个目录,
            来表示项目或应用中所储存静态文件的目录
	3、访问静态文件
		1、直接使用 localhost:8000/static/****
			<img src="http://localhost:8000/static/***">
			<img src="/static/***">
		2、使用 {% static %}访问静态文件
			{% static %}表示的就是静态文件访问路径
			1、在模板的最顶层增加
				{% load static %}
			2、在使用静态文件时
				<img src="{% static '具体路径'%}">
				ex:
					<img src="{% static 'images/huiyuan.jpg'%}">

day2/day2/settings.py

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 = ‘!&$qv@()^z=!@eux00yt8r2l#1l$0-ief_o46gr=xt6db##-1@’

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’,
‘news’,
‘index’,
‘music’,
‘sport’,
]

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 = ‘day2.urls’

TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [],
‘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 = ‘day2.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/’


day2/day2/urls.py

from django.conf.urls import url, include
from django.contrib import admin

主路由配置文件

urlpatterns = [
# 请求路径 http://localhost:8000/
# 一律都交给index应用中的urls模块去处理
url(r’^’, include(‘index.urls’)),
url(r’^admin/’, admin.site.urls),
# 请求路径 http://localhost:8000/news/
# 一律都交给news应用中的urls模块去处理
url(r’^news/’, include(‘news.urls’)),
# 请求路径 http://localhost:8000/music/
# 一律都交给music应用中的urls模块去处理
url(r’^music/’, include(‘music.urls’)),
# 请求路径 http://localhost:8000/sport/
# 一律都交给sport应用中的urls模块去处理
url(r’^sport/’, include(‘sport.urls’)),

]

day2/index/templates/01_template.html

Document

这是我的第一个模板

----------------------------------------------------- # day2/index/templates/02_var.html {{title}}

这是一个模板

标题为:{{title}}

---------------------------------------------------- # day2/index/templates/03_exer.html {{title}}

书名:<<{{title}}>>

作者:{{author}}

主题:{{topic}}

-------------------------------------------------- # day2/index/templates/04_var.html Document {% for name in list %} {% comment %} ------------------------------------------------- # day2/index/urls.py

from django.conf.urls import url
from .views import *

当访问路径 http://localhost:8000/

请求会转交到此处

urlpatterns = [
url(r’^,indexviews),url(rlogin/&#x27;, index_views), url(r&#x27;^login/’, login_views),
]

urlpatterns += [
url(r’^01_getTemp/,getTempviews),url(r02getTemp/&#x27;, getTemp_views), url(r&#x27;^02_getTemp/’, render_views),
url(r’^03_var/,varviews),url(r04varExer/&#x27;, var_views), url(r&#x27;^04_varExer/’, varExer_views),
url(r’^05_varTemp/$’, varTemp_views),
]

day2/index/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

Create your views here.

def index_views(request):
return HttpResponse(‘index应用中的index视图’)

def login_views(requset):
return HttpResponse(‘index应用中的login视图’)

def getTemp_views(request):
# 1.通过 loader 加载模板
t = loader.get_template(‘01_template.html’)
# 2.将模板对象渲染成字符串
html = t.render()
# 3.将字符串响应给客户端
return HttpResponse(html)

def render_views(request):
return render(request, ‘01_template.html’)

def var_views(request):
dic = {
‘title’: ‘测试模板’,
‘content’: ‘模板的内容’,
}
return render(request, ‘02_var.html’, dic)

def varExer_views(request):
title = ‘水浒传’
author = ‘施耐庵’
topic = ‘105个男人和3个女人的故事’

# dic = {
#     'title':title,
#     'author':author,
#     'topic':topic,
# }
# locals() 将当前函数内的局部变量封装成一个字典,效果同上
return render(request, '03_exer.html', locals())

def fun(a, b):
return a + b

class A(object):
a = ‘A 类中的 a 属性’

def f(self):
    return 'This is the method of A'

def varTemp_views(request):
l = [‘老舍’, ‘朱自清’, ‘莫言’, ‘泰戈尔’, ‘奥斯特洛夫斯基’]
t = (‘冰心’, ‘韩寒’, ‘郭敬明’)
d = {‘A’: ‘Andrew’, ‘B’: ‘BEYOND’, ‘C’: ‘Controller’}
return render(request, ‘04_var.html’, {
‘num’: 10086,
‘str’: ‘中国移动’,
‘list’: l,
‘tup’: t,
‘dic’: d,
‘fun’: fun(25, 52),
‘A’: A(),
})

day2/music/urls.py

from django.conf.urls import url
from .views import *

请求路径是 http://localhost:8000/music/的时候

请求才会到此

urlpatterns = [
url(r’^index/$’, index_views),
]

day2/music/views.py

from django.shortcuts import render
from django.http import HttpResponse

Create your views here.

def index_views(request):
return HttpResponse(‘music应用中的index’)

day2/news/urls.py

from django.conf.urls import url
from .views import *

只有请求路径是 http://localhost:8000/news/

才能进入到此路由配置

urlpatterns = [
# 请求路径是 show 的时候,则交给show_views去处理
url(r’^show/KaTeX parse error: Expected 'EOF', got '#' at position 21: …ow_views), #̲ 请求路径是 index 的时…’, index_views),
]

day2/news/views.py

from django.shortcuts import render
from django.http import HttpResponse

Create your views here.

def show_views(request):
return HttpResponse(‘这是news应用中的show_views视图’)

def index_views(request):
return HttpResponse(‘这是news应用中的index’)

day2/sport/templates/01_params.html

Document

去往02_name

通过别名找到 02_name
去往02_name

去往03_name

通过别名找到 03_name并传参
去往03_name

------------------------------------------------------ # day2/sport/urls.py

from django.conf.urls import url
from .views import *

请求地址 http://localhost:8000/sprot/

请求会转发到此处

urlpatterns = [
url(r’^index/,indexviews),url(r01params/&#x27;, index_views), url(r&#x27;^01_params/’, params_views),
url(r’^02_name/$’, name_views, name=‘page2’),
url(r’^03_name/(\d{4})’, name_arg_views, name=‘page3’)
]


day2/sport/views.py

from django.shortcuts import render
from django.http import HttpResponse

Create your views here.

def index_views(request):
return HttpResponse(‘sport应用中的index’)

def params_views(request):
return render(request, ‘01_params.html’)

def name_views(request):
return HttpResponse(‘已经成功到达02_name’)

def name_arg_views(request, num):
return HttpResponse(‘传递的参数为:’ + num)

manage.py

#!/usr/bin/env python3
import os
import sys

if name == “main”:
os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “day2.settings”)
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn’t import Django. Are you sure it’s installed and "
"available on your PYTHONPATH environment variable? Did you "
“forget to activate a virtual environment?”
)
raise
execute_from_command_line(sys.argv)

    作业:
		1、完善fruitday项目中的login登录页面
发布了208 篇原创文章 · 获赞 8 · 访问量 6189
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览