django学习笔记4
利用模板创建项目
1.创建template文件夹中创建hello.html

hello.html中内容为
<h1>{{hello}}</h1>
2.修改setting.py中路径
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ]
3.修改view.py
from django.shortcuts import render def hello(request): context = {} context['hello'] = 'Hello world!' return render(request,'hello.html',context)
4.修改urls.py
urlpatterns = [ url(r'^hello/$','myapp.view.hello') ]
5.打开浏览器输入http://localhost:8000/hello/

模板继承
模板可以使用继承的方法实现复用
1.在template文件夹中创建base.html
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
{% block mainbody %}
<p>original</p>
{% endblock %}
</body>
</html>
{%block%}告诉模板模板引擎,此部分可被重载
2.修改hello.html中内容
{% extends "base.html" %}
{% block mainbody %}
<p>继承了base.html</p>
{% endblock %}
首先声明继承base.html。替换base.html中{% block %}名称相同的部分。
3.浏览器中输入http://localhost:8000/hello/

django连接数据库
本文中使用postgresql数据库,在前文中已经创建了用户ge,本次在django中进行测试
1.打开setting.py文件,找到databases字典,填写以下内容
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'ge',
}
}
更改了ENGINE类型,以及NAME名称
2.检验数据库是否连接成功
打开终端,进入到项目的根目录,执行shell命令
gedeMacBook-Pro:myapp ge$ python manage.py shell Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.db import connection >>> cursor = connection.cursor()
没有报错信息,说明连接成功

浙公网安备 33010602011771号