Django介绍:
Django简介:

为什么使用Django?

知识储备:

学习目标:


DJango初体验:
1.安装DJango:

sudo pip install -i https://pypi.doubanio.com/simple/ Django
使用国内镜像
创建Django项目
django-admin startproject demo
会在目录下产生一个manage.py管理脚本
python manage.py runserver 0.0.0.0:8080 #局域网内的机子可以访问本机ip的8080

mac访问虚拟机中的Ubuntu里建的website
2.Django工程目录:


_init_py:�声明了这个子目录上是一个python模块
2.1 Django的应用目录大致结构:

2.1.1 创建应用:
python manage.py startapp blog

2.1.2 添加应�用:
在settings.py 添加

2.1.3 应用目录详解:

_init_py:�声明了这个子目录上是一个python模块
views.py:声明了视图逻辑
models.py:声明了数据模型
admin.py:将数据模型注册到Django内置的管理模块中
tests.py:单元测试
migrations:用于数据迁移
旧版本代码:

新版本代码:


!(Django1.10需要修改的地方)[http://stackoverflow.com/questions/38394598/typeerror-view-must-be-a-callable-or-a-list-tuple-in-the-case-of-include]
!(Django 创建第一个项目)[http://www.runoob.com/django/django-first-app.html]
3.Django概述(重要概念)

Django开发-基础篇
DJango模板语法及使用:
什么是模板
模板是一个文本,用于分离文档和表现内容,通常用于生成HTML。
<html>
<head>template</head>
<body>
<p>Hello{{name}}</p>
<ul>
{% for item in itemlist %}
<li>{{item}}</li>
{% endfor %}
</ul>
{% if status %}
<p> I love python </p>
{% else %}
<p> I love django </p>
{% endif %}
</body>
模板使用方法:
1.用原始的模板代码字符串创建一个Template对象
2.调用模板对象的render方法,并且传入一套变量context
python manage.py shell
from django import template
t = template.Template('hello,{{name}}') #创建一个变量name
c = template.Context({'name':'django'}) #创建了一个context并传入一个name的值
print t.render(c) #调用render方法来渲染
一旦你创建了一个template对象,你就可以用context处理器来传递数据给它,最用调用render()方法来渲染它
模板中过滤器:
过滤器就是将模板中的变量过滤一遍,在变量显示前修改它的一个方法。
如:下列代码中,upper就是一个过滤器:将name这个变量转化为全部为大写字母的格式。
{{name|upper}}
模板的加载 :
Django提供了一种使用方便且功能强大的API,用于解决模板加载调用过程的问题。
创建一个文件夹templates,并写入模板:

在settings.py写入
import os
TEMPLATES_DIRS = os.path.join(os.path.dirname(__file__),'templates')
#可以根据路径查找模板
在manage.py shell 输入:
from django.template.loader import get_template
t = get_template("2.html")
t
输出:
<django.template.backends.django.Template at 0x7f6e2da0d790>
#说明模板使用成功
模型开发与数据库交互:
使用原生方法连接数据库:
from django.test import TestCase
import MySQLdb
db = MySQLdb.connect(user = 'root',password= 'root',db ='test')#连接数据库
cursor = db.cursor() #创建一个游标
cursor.execute('select * from table')#使用sql语句
result = cursor.fetchall() #获取返回的结果
cursor.close()
db.close() #关闭数据库连接
配置settings.py文件:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',#选择数据库引擎
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'USER':'root',
'PASSWORD':'root',
'NAME':'test',
'HOST':'localhost'
}
}
在模型中使用数据库:
修改models.py:
from django.db import models
class Mysite(models.Model):
#定义一个title,字符串类型
title = models.CharField(max_length=100)
url = models.URLField()
author = models.CharField(max_length=100)
#定义一个num,整形
num = models.IntegerField(max_length=10)
检查模型:
python manage.py check
将模型同步到数据库中:
python manage.py makemigrations
python manage.py migrate

django1.10的很多操作跟现在出版的书里的命令都不一样了
安装python模块时出现:error: Setup script exited with error: command 'gcc' failed with exit status 1
mysql-python安装时EnvironmentError: mysql_config not found
模型开发与数据库交互--数据处理:
1.基本数据访问
from blog.models import *
m = Mysite.objects.all()
m
# Out[6]: <QuerySet []> #数据为空,输出空列表
2.插入和更新数据
m = Mysite(title='django',num=2)
m.save()
m = Mysite.objects.all() #查询所有
m
#Out[10]: <QuerySet [<Mysite: Mysite object>]>
m[0].title
#Out[11]: u'django'
3.数据过滤
m = Mysite.objects.get(num=2)
m
#Out[13]: <Mysite: Mysite object>
m.title
#Out[14]: u'django'
4.数据排序
#插入多条�数据
m = Mysite(title='django',num=3)
m.save()
m = Mysite(title='django',num=9)
m.save()
m = Mysite(title='django',num=1)
m.save()
#以num进行排序
m = Mysite.objects.all().order_by("num")
m[0].num
#Out[30]: 1L
5.更新多个对象,删除对象等
m = Mysite.objects.get(num=2)
m.title
#Out[32]: u'django'
m.title = 'python' #更新数据
m.delete() #获取对象后进行删除即可
Django 的后台管理及表单类介绍:
Django的自动管理界面:通过读取你模式中的元数据,提供一个强大而且可以使用的界面。
例子:
修改views.py,编写视图函数:
from blog.models import *
from blog.forms import *
from django.http import HttpResponse
from django.shortcuts import render_to_response
def hello(request):
if request.method == 'POST':
form = Mybook(request.POST)#将post的数据填到表单里面
if form.is_valid(): #验证是否有效
data = form.cleaned_data
title = data['title'] #取其中title数据
return HttpResponse(title)
form = Mybook()##如果是get请求,则返回这个页面
return render_to_response('1.html',{'form':form})
添加froms.py:
from django import forms
class Mybook(forms.Form):
name = forms.CharField()
author = forms.CharField()
date = forms.CharField()
添加1.html:
<html>
<body>
<form method='post'>
{{form.as_p}}
<input type = "submit" name = "ok">
</from>
</body>
</html>

网友评论