Python web开发笔记五:Django开发进阶一

理解上下文

render(request,x.html,context)
request:请求的固定写法。
x.html:模板,需要填补丁的模板。
context:上下文,填充模板的补丁。

模板的使用流程

  • 写模板,创建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增加:
<span class="grey">{{ article.date|date:"Y-m-d" }}</span>

模板继承

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<year>\d{4})/(?P<month>\d{1,2})/$','get_news_list',name="news_archive" )

<year> <month> 在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') # 包含查询
[<Post: Sample title>, <Post: 4th title of post>] 
# 注在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() 返回布尔值

拓展阅读:
课堂操作内容文档

备注
该笔记源自网易微专业《Python web开发》1.2节
本文由EverFighting创作,采用 知识共享署名 3.0 中国大陆许可协议进行许可。

    原文作者:everfight
    原文地址: https://segmentfault.com/a/1190000008791508
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞