模板的运用流程
写模板,创立Template目标,用模板言语进行修正。
创立Context,context是一组字典,用来传递数据给Template目标。
调用Template目标的render()办法传递context来填充模板。
创立并运用模板
独自创立templates、staitc文件夹,将之前写的前端文件怎么放入Django项目。
网页放入tempaltes,一切的静态文件放入static中。(静态文件是指网站中的 js, css, 图片,视频等)
修正setting,TEMPLATES,DIRS:[os.path.join(BASE_DIR,'templates').replace('\','/')], (注意逗号不能够少)
html最上方参加{% load staticfiles %},在模板中引进静态文件,修正模板中的固定地址改为动态地址。({% static 'css/semantic.css' %})
模板言语
模板言语分为:模板变量,模板标签,模板过滤器。
模板变量:
{{ value }},{{ Person.name }}
模板标签:
{% for item in list %} {{ item }} {% endfor %} {% for key, value in dict.items %} {{ key }}: {{ value }} {% endfor %} {% if today_is_weekend %} <p>Welcome to the weekend!p> {% else %} <p>Get back to work.p> {% endif %}
注:标签可以多重进行嵌套。
其他:
{% forloop.first %}是一个布尔值。在第一次履行循环时该变量为True {% forloop.last %}是一个布尔值;在最终一次履行循环时被置为True。
模板过滤器:
{{ value|default:"nothing" }} 假如为空则显现nothing的款式。 {{ value|truncatewords:200 }} 只显现前200个字符。 {{ name|lower }} 功用是转化文本为小写。
事例
运用 django 的'日期字段'给每篇文章增加类似图中的一个发布日期,格式是「2016-11-05」
model增加: class Aritcle(models.Model): date = models.DateField(auto_now=True) html增加: class="grey">{{ article.date|date:"Y-m-d" }}
模板承继
extends标签
界说一个父模板为base.html,写出HTML的骨架,将需要子块修正的当地用{% block %}{% endblock %}标出。
子模板运用{% extends "base.html" %}将内容填写进这些空白的内容块。
模板承继允许你建立一个基本的”骨架”模板, 它包括你一切最常用的站点元素并界说了一些可以被子模板覆盖的block。
假如你需要在子模板中引用父模板中的 block 的内容,运用 “{{ block.super }}“ 变量.这在你希望在父模板的内容之后增加一些内容时会很有用.(你不必彻底覆盖父模板的内容.)
include标签
{% include %}该标签允许在(模板中)包括其它的模板的内容。
标签的参数是所要包括的模板称号,可所以一个变量,也可所以用单/双引号硬编码的字符串。
每逢在多个模板中呈现相同的代码时,就应该考虑是否要运用 {% include %} 来减少重复。
stackoverflow问题:{% include %} vs {% extends %} in django templates?
Extending allows you to replace blocks (e.g. "content") from a parent template instead of including parts to build the page (e.g. "header" and "footer"). This allows you to have a single template containing your complete layout and you only "insert" the content of the other template by replacing a block.
If the user profile is used on all pages, you'd probably want to put it in your base template which is extended by others or include it into the base template. If you wanted the user profile only on very few pages, you could also include it in those templates. If the user profile is the same except on a few pages, put it in your base template inside a block which can then be replaced in those templates which want a different profile.
模板注释
注释运用{# #}注释不能跨多行 eg: {# This is a comment #}
urls相关
urls中界说链接(三种)
Function views Add an import: from my_app import views Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views Add an import: from other_app.views import Home Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf Import the include() function: from django.conf.urls import url, include Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
url的name特点
url(r'^add/$', calc_views.add, name='add'),
这儿的name可以用于在 templates, models, views ……中得到对应的网址,相当于“给网址取了个姓名”,只需这个姓名不变,网址变了也能通过姓名获取到。
url正则表达式
url(r'^(?P\d{4})/(?P\d{1,2})/$','get_news_list',name="news_archive" )
在view的参数取得 如:def index(request,year,month)
url的include用法
(r'^weblog/', include('mysite.blog.urls')), (r'^photos/', include('mysite.photos.urls')),
指向include()的正则表达式并不包括一个$(字符串结束匹配符)。每逢Django 遇到include()时,它将截断匹配的URL,并把【剩下】的字符串发往被包括的 URLconf 作进一步处理。
创立运用后台
运用django自带的后台,可以可视化办理后台的数据。
创立超级办理员
python manage.py createsuperuser # 设置用户名,暗码。
注册自界说model
from models import People admin.site.register(People)
修正显现字段
办理后台默许显现People Obejct,在model中增加返回值办法,修正显现作用。
def __str__(self): return self.name
修正后台暗码的办法
python manage.py createsuperuser --username admin python manage.py changepassword admin
admin显现自界说字段
from django.contrib import admin from .models import Article class ArticleAdmin(admin.ModelAdmin): list_display = ('title','pub_date','update_time',) admin.site.register(Article,ArticleAdmin)
引进数据
Django ORM对数据库进行操作,数据库操作完成之后,记得要进行save()保存。
数据库操作
Article.objects.all() 获取表中一切目标 Aritcle.objects.get(pk=1) # Django中pk=primary key,和id等价。 Article.objects.filter(pub_date__year=2006) # 运用过滤器获取特定目标 Article.objects.all().filter(pub_date__year=2006) #与上方一致 ## 链式过滤 >>> Aritcle.objects.filter( ... headline__startswith='What' ... ).exclude( ... pub_date__gte=datetime.date.today() ... ).filter( ... pub_date__gte=datetime(2005, 1, 30) ... ) Article.objects.create(author=me, title='Sample title', text='Test') #创立目标 Person.objects.get_or_create(name="WZT", age=23) # 避免重复很好的办法 Article.objects.all()[:5] 记录前5条 Person.objects.all().reverse()[:2] # 最终两条 Person.objects.all().reverse()[0] # 最终一条 >>> Post.objects.filter(title__contains='title') # 包括查询 [,] # 注在title与contains之间有两个下划线字符 (_)。 # Django的ORM运用此语法来分隔字段称号 ("title") 和操作或筛选器("contains")。 Post.objects.order_by('-created_date') # 目标进行排序,默许升序,添负号为降序。 Person.objects.filter(name__iexact="abc") # 不区别大小写 Person.objects.filter(name__exact="abc") # 严格等于 Person.objects.filter(name__regex="^abc") # 正则表达式 Person.objects.filter(name__iregex="^abc") # 不区别大小写 Person.objects.exclude(name__contains="WZ") # 扫除 Person.objects.filter(name__contains="abc").exclude(age=23 #找出称号含有abc, 可是扫除年龄是23岁的
QuerySet创立目标的四种办法
Author.objects.create(name="WeizhongTu", email="tuweizhong@163.com twz = Author(name="WeizhongTu", email="tuweizhong@163.com") twz.save() twz = Author() twz.name="WeizhongTu" twz.email="tuweizhong@163.com" Author.objects.get_or_create(name="WeizhongTu", email="tuweizhon“) # 返回值(object, True/False)
QuerySet是可迭代的
es = Entry.objects.all() for e in es: print(e.headline)
查看目标是否存在
Entry.objects.all().exists() 返回布尔值
拓宽阅览:
课堂操作内容文档