1、创建 Django 工程
- django-admin startproject 工程名
2、创建 App
- cd 工程名
- python manage.py startapp cmdb
3、静态文件配置
编辑 project.settings.py,追加以下内容
- STATICFILES_DIRS = (
- os.path.join(BASE_DIR, "static"),
- )
4、模板路径配置
- DIRS ==> (os.path.join(BASE_DIR, 'templates'),)
5、settings 中, 注释 csrf
- MIDDLEWARE_CLASSES = (
- #'django.middleware.csrf.CsrfViewMiddleware',
- )
6、定义路由规则,在 url.py 中定义用户访问的 url 由哪个函数来处理请求
- url.py
- "login" --> 函数名
7、定义视图函数,在 views.py 中定义函数
- def func(reuest):
- # request.method GET/POST
- # http://127.0.0.1:8000/home?nid=123&name=bob
- # request.GET.get('',None) #获取请求发来的数据
- # request.POST.get('',None)
- # return HttpResponse("字符串")
- # return Render(request, 'html模板路径',{"user_list": USER_LIST})
- # return redirect('只能填URL,例如:/home')
8、模板渲染
Django 特殊的模板语言,例如:
-- 变量名取值 --
在 views.py 中定义好变量和对应的值,在 template 的 html 页面中通过 {{var_name}} 的方式来取值
- def func(request):
- return render(request,"index.html",{'current_user': "bob"})
- index.html
- <html>
- <body>
- <div>{{ current_user }}</div>
- </body>
- </html>
--For 循环取值 --
在 views.py 中定义好列表和值,在 template 的 html 页面中通过 {{for 循环}} 的方式来取值
- def func(request):
- return render(request,"index.html",{
- 'current_user': "bob",
- 'user_list':['bob','aaa','bbb']})
- index.html
- <html>
- <body>
- <div>{{ current_user }}</div>
- <ul>
- {% for row in user_list %}
- <li>{{ row }}</li>
- <% endfor %>
- </ul>
- </body>
- </html>
-- 索引取值 --
在 views.py 中定义好字典和值,在 template 的 html 页面中通过 {{var_name.key}} 的方式来取值
- def func(request):
- return render(request,"index.html",{
- 'current_user': "bob",
- 'user_list': ['bob','aaa','bbb'],
- 'user_dict': ['k1': 'v1', 'k2': 'v2']
- })
- index.html
- <html>
- <body>
- <div>{{ current_user }}</div>
- <a>{{ user_list.1 }}</a> //对于列表直接用索引取值
- <a>{{ user_dict.k1 }}</a> //对于字典,要用key取值
- <a>{{ user_dict.k2 }}</a>
- </body>
- </html>
-- 条件取值 --
{% if %}
{% if %}
{% endif %}
{% else%}
{% else %}
{% endif %}
- def func(request):
- return render(request,"index.html",{
- 'current_user': "bob",
- 'age': 18,
- 'user_list': ['bob','aaa','bbb'],
- 'user_dict': ['k1': 'v1', 'k2': 'v2']
- })
- index.html
- <html>
- <body>
- <div>{{ current_user }}</div>
- <a>{{ user_list.1 }}</a> //对于列表直接用索引取值
- <a>{{ user_dict.k1 }}</a> //对于字典,要用key取值
- <a>{{ user_dict.k2 }}</a>
- {% if age %}
- <a>有年龄</a>
- {% if age > 16 %}
- <a>老男人</a>
- {% else %}
- <a>小鲜肉</a>
- {% endif %}
- {% else %}
- <a>无年龄</a>
- {% endif %}
- </body>
- </html>
模板的工作流程:
过滤器
模板过滤器是变量显示前转换它们的值的方式,看起来像下面这样
- {
- { name | lower
- }
- }
这将显示通过 lower 过滤器过滤后 {{name}} 变量的值,它将文本转换成小写使用 (|) 管道来申请一个过滤器
过滤器可以串成链,即一个过滤器的结果可以传向下一个,下面是 escape 文本内容然后把换行转换成 p 标签的习惯用法
- {
- { my_text | escape | linebreaks
- }
- }
更过关于 Django 模板的资料,请访问:
http://blog.csdn.net/zhangxinrun/article/details/8095118/
来源: http://www.bubuko.com/infodetail-2098434.html